diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index 92a6828a06..dda4ffc63f 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2.3.84 + +### Patch Changes + +- feat(sdk): price a comment's RC cost the way the chain does (#1486) + ## 2.3.83 ### Patch Changes diff --git a/packages/sdk/dist/browser/index.d.ts b/packages/sdk/dist/browser/index.d.ts index 315b6b4ac5..e8c20255c7 100644 --- a/packages/sdk/dist/browser/index.d.ts +++ b/packages/sdk/dist/browser/index.d.ts @@ -1590,6 +1590,7 @@ declare const QueryKeys: { readonly resourceCredits: { readonly account: (username: string) => string[]; readonly stats: () => string[]; + readonly resourceParams: () => string[]; }; readonly points: { readonly points: (username: string, filter: number) => (string | number)[]; @@ -1662,6 +1663,19 @@ declare function vestsToHp(vests: number, hivePerMVests: number): number; declare function isEmptyDate(s: string | undefined): boolean; +/** + * UTF-8 byte length of a string. + * + * `TextEncoder` is missing on some runtimes the SDK ships to (React Native / + * Hermes), and `String.length` is NOT a substitute: it counts UTF-16 code + * units, so anything non-ASCII is undercounted. Where that number feeds an RC + * estimate, undercounting means telling someone a post is affordable when the + * chain will reject it. + */ +declare function utf8ByteLength(value: string): number; +/** Byte length of Hive's unsigned LEB128 varint for `value`. */ +declare function varintByteLength(value: number): number; + interface AccountFollowStats { follower_count: number; following_count: number; @@ -5530,6 +5544,82 @@ declare function getAccountRcQueryOptions(username: string): _tanstack_react_que }; }; +/** Shape returned by `rc_api.get_resource_params`. Numbers arrive as strings. */ +interface RcPriceCurveParams { + coeff_a: string | number; + coeff_b: string | number; + shift: string | number; +} +interface RcResourceDynamicsParams { + resource_unit: string | number; + budget_per_time_unit: string | number; + pool_eq: string | number; + max_pool_size: string | number; +} +interface RcResourceParamEntry { + resource_dynamics_params: RcResourceDynamicsParams; + price_curve_params: RcPriceCurveParams; +} +/** + * Per-operation and per-transaction sizing constants. Only the members this + * module needs are declared; the node returns many more. + */ +interface RcSizeInfo { + resource_state_bytes: { + comment_base_size: number; + comment_permlink_char_size: number; + comment_beneficiaries_member_size: number; + transaction_base_size: number; + [key: string]: number; + }; + resource_execution_time: { + comment_time: number; + comment_options_time: number; + transaction_time: number; + verify_authority_time: number; + [key: string]: number; + }; + [key: string]: Record; +} +interface RcResourceParams { + resource_params: Record; + size_info: RcSizeInfo; +} +/** + * Resource order is consensus-defined (`HIVE_RC_NUM_RESOURCE_TYPES`) and the + * `pool`, `share` and `budget` arrays in rc_stats are indexed by it. + */ +declare const RC_RESOURCE_NAMES: readonly ["resource_history_bytes", "resource_new_accounts", "resource_market_bytes", "resource_state_bytes", "resource_execution_time"]; +type RcResourceName = (typeof RC_RESOURCE_NAMES)[number]; +interface RcCostBreakdown { + resource: RcResourceName; + usage: number; + cost: number; +} + +/** + * Curve coefficients and sizing constants used to price resource usage. + * + * These only change at a hardfork, so the entry is kept for the session: + * `gcTime: Infinity` is the one value that schedules no gc timer at all, so it + * does not hold a request's query cache open on the server the way a long + * finite window would. + * + * `staleTime` stays bounded on purpose. Making it infinite too would mean a + * long-lived session keeps pricing with pre-hardfork coefficients forever, + * quietly producing wrong RC estimates with no way to recover short of a + * reload. A day is long enough that this is effectively never refetched, and + * short enough that a hardfork corrects itself. + */ +declare function getRcResourceParamsQueryOptions(): _tanstack_react_query.OmitKeyof<_tanstack_react_query.UseQueryOptions, "queryFn"> & { + queryFn?: _tanstack_react_query.QueryFunction | undefined; +} & { + queryKey: string[] & { + [dataTagSymbol]: RcResourceParams; + [dataTagErrorSymbol]: Error; + }; +}; + interface RcStats { block: number; budget: number[]; @@ -5645,6 +5735,88 @@ interface RcPrecheckResult { */ declare function estimateRcPrecheck({ rcAccount, rcStats, operation, buffer, }: RcPrecheckInput): RcPrecheckResult; +/** + * Port of `resource_credits::compute_cost` (libraries/chain/rc/rc_utility.cpp). + * + * BigInt is required, not stylistic: `coeff_a` is ~1.05e19, well past + * Number.MAX_SAFE_INTEGER, so float arithmetic loses the low bits and the + * result drifts. + */ +declare function computeResourceCost(curve: RcPriceCurveParams, pool: number, resourceCount: number, regenShare: number): number; +interface CommentResourceUsageInput { + /** Byte length of the serialized transaction. */ + transactionBytes: number; + permlinkLength: number; + /** Signatures on the transaction; a normal post carries one. */ + signatures?: number; + /** + * Beneficiary count on the companion comment_options, when publish appends + * one. The chain counts resources for every operation in the transaction, + * not just the comment. + */ + beneficiaries?: number; + hasCommentOptions?: boolean; +} +/** + * Port of the `comment_operation` and `comment_options_operation` arms of + * `count_resources` (libraries/chain/rc/resource_count.cpp). Reproduces the + * chain's numbers exactly, see the spec. + */ +declare function countCommentResourceUsage({ transactionBytes, permlinkLength, signatures, beneficiaries, hasCommentOptions }: CommentResourceUsageInput, sizeInfo: RcSizeInfo): Record; +interface CommentLike { + author: string; + permlink: string; + parent_author: string; + parent_permlink: string; + title: string; + body: string; + json_metadata: string; +} +/** A beneficiary route as it appears in comment_options extensions. */ +interface BeneficiaryRoute { + account: string; + weight: number; +} +/** + * The comment_options operation publish appends when the author sets + * beneficiaries or a non-default reward split. + */ +interface CommentOptionsLike { + beneficiaries?: BeneficiaryRoute[]; +} +interface CommentTransactionInput { + op: CommentLike; + /** Present when publish appends comment_options for beneficiaries or rewards. */ + options?: CommentOptionsLike; + signatures?: number; +} +/** + * Serialized size of the transaction that will carry this comment. + * + * This models Hive's binary encoding rather than approximating it: a fixed + * header, one varint-prefixed field per string, and 65 bytes per signature. + * Verified byte-exact against eight real transactions read back with + * `get_transaction_hex`, including one carrying comment_options. + */ +declare function estimateCommentTransactionBytes({ op, options, signatures }: CommentTransactionInput): number; +interface EstimateCommentRcCostInput { + op: CommentLike; + /** Companion comment_options, when the author set beneficiaries or rewards. */ + options?: CommentOptionsLike; + rcParams: RcResourceParams | undefined; + rcStats: Pick | undefined; + signatures?: number; +} +interface CommentRcCostEstimate { + /** False until both queries have resolved; callers must not warn on this. */ + ready: boolean; + cost: number; + transactionBytes: number; + breakdown: RcCostBreakdown[]; +} +/** Total RC the chain will charge to broadcast this comment. */ +declare function estimateCommentRcCost({ op, options, rcParams, rcStats, signatures }: EstimateCommentRcCostInput): CommentRcCostEstimate; + interface GetGameStatus { key: string; remaining: number; @@ -9321,4 +9493,4 @@ interface PollVotePayload { } declare function usePollVote(username: string | undefined, auth?: AuthContextV2, broadcastMode?: BroadcastMode): _tanstack_react_query.UseMutationResult; -export { ACCOUNT_OPERATION_GROUPS, ALL_ACCOUNT_OPERATIONS, ALL_NOTIFY_TYPES, type AccountBookmark, type AccountDelegations, type AccountFavorite, type AccountFollowStats, type AccountKeys, type AccountNotification, type AccountProfile, type AccountRelationship, type AccountReputation, type AggregatedBalanceEntry, type AiAssistParams, type AiAssistPrice, type AiAssistResponse, type AiGenerationPrice, type AiGenerationRequest, type AiGenerationResponse, type AiImagePowerTier, type AiImagePriceResponse, type AiTranscribeParams, type AiTranscribePrice, type AiTranscribeResponse, type Announcement, type ApiBookmarkNotification, type ApiDelegationsNotification, type ApiFavoriteNotification, type ApiFollowNotification, type ApiInactiveNotification, type ApiMentionNotification, type ApiNotification, type ApiNotificationSetting, type ApiPayoutsNotification, type ApiReblogNotification, type ApiReferralNotification, type ApiReplyNotification, type ApiResponse, type ApiScheduledPublishedNotification, type ApiSpinNotification, type ApiTransferNotification, type ApiVoteNotification, type ApiWeeklyEarningsNotification, type Asset, AssetOperation, type AuthContext, type AuthContextV2, type AuthMethod, type AuthorReward, Authority, type AuthorityLevel, type AuthorityType, BROADCAST_INCLUSION_DELAY_MS, type BalanceAggregationGranularity, type BalanceCoinType, type BalanceHistoryEntry, type BalanceHistoryResponse, type Beneficiary, type BlogEntry, type BoostPlusAccountPrice, type BoostPlusPayload, type BroadcastMode, BroadcastResult, type BuildProfileMetadataArgs, type BuiltSearchQuery, BuySellTransactionType, CONFIG, type CancelTransferFromSavings, type CantAfford, type CheckUsernameWalletsPendingResponse, type ClaimAccountPayload, type ClaimEngineRewardsPayload, type ClaimInterestPayload, type ClaimRewardBalance, type ClaimRewardsPayload, type CollateralizedConversionRequest, type CollateralizedConvert, type CommentBenefactor, type CommentPayload, type CommentPayoutUpdate, type CommentReward, type Communities, type Community, type CommunityProps, type CommunityRewardsRegisterPayload, type CommunityRole, type CommunityTeam, type CommunityType, ConfigManager, type ConversionRequest, type ConvertPayload, type CreateAccountPayload, type CrossPostPayload, type CurationDuration, type CurationItem, type CurationReward, type CurrencyRates, type DailyCheckinQuest, type DailyContentQuest, type DailyQuest, type DelegateEngineTokenPayload, type DelegateRcPayload, type DelegateVestingShares, type DelegateVestingSharesPayload, type DelegatedVestingShare, type DeleteCommentPayload, type DeletedEntry, type Draft, type DraftMetadata, type DraftRewardType, type DraftsWrappedResponse, type DynamicProps$1 as DynamicProps, index as EcencyAnalytics, EcencyQueriesManager, type EffectiveCommentVote, type EngineMarketOrderPayload, EntriesCacheManagement, type Entry$1 as Entry, type EntryBeneficiaryRoute, type EntryHeader, type EntryStat, type EntryVote, ErrorType, type FeedHistoryItem, type FillCollateralizedConvertRequest, type FillConvertRequest, type FillOrder, type FillRecurrentTransfers, type FillTransferFromSavings, type FillVestingWithdraw, type Follow, type FollowPayload, type Fragment, type FriendSearchResult, type FriendsPageParam, type FriendsRow, type FullAccount, type GameClaim, type GeneralAssetInfo, type GeneralAssetTransaction, type GenerateImageParams, type GetGameStatus, type GetRecoveriesEmailResponse, type GrantPostingPermissionPayload, HIVE_ACCOUNT_OPERATION_GROUPS, HIVE_OPERATION_LIST, HIVE_OPERATION_NAME_BY_ID, HIVE_OPERATION_ORDERS, type HiveBasedAssetSignType, type HiveEngineMarketResponse, type HiveEngineMetric, type HiveEngineOpenOrder, type HiveEngineOrderBookEntry, HiveEngineToken, type HiveEngineTokenBalance, type HiveEngineTokenInfo, type HiveEngineTokenMetadataResponse, type HiveEngineTokenStatus, type HiveEngineTransaction, type HiveHbdStats, type HiveMarketMetric, type HiveOperationFilter, type HiveOperationFilterKey, type HiveOperationFilterValue, type HiveOperationGroup, type HiveOperationName, HiveSignerIntegration, type HiveTransaction, type HsTokenRenewResponse, INTERNAL_API_TIMEOUT_MS, type IncomingDelegation, type IncomingRcDelegation, type IncomingRcResponse, type Interest, type JsonMetadata, type JsonPollMetadata, type Keys, type LeaderBoardDuration, type LeaderBoardItem, type LimitOrderCancel, type LimitOrderCancelPayload, type LimitOrderCreate, type LimitOrderCreatePayload, MAX_SEARCH_QUERY_LENGTH, MAX_SEARCH_TAGS, type MarketCandlestickDataItem, type MarketData, type MarketStatistics, type MedianHistoryPrice, type MutePostPayload, NaiMap, NotificationFilter, NotificationViewType, type Notifications, NotifyTypes, OPERATION_AUTHORITY_MAP, type OpenOrdersData, Operation, type OperationGroup, OperationName, OrderIdPrefix, type OrdersData, type OrdersDataItem, type OutgoingDelegation, POLLS_PROTOCOL_VERSION, type PageStatsResponse, type PaginationMeta, type ParsedChainError, type Payer, type PeriodQuest, type PinPostPayload, type PlatformAdapter, type PointTransaction, PointTransactionType, type Points, type PointsResponse, type Poll, type PollChoice, type PollChoiceVotes, PollPreferredInterpretation, type PollStats, type PollVotePayload, type PollVoter, type PortfolioResponse, type PortfolioWalletItem, type PostTip, type PostTipsResponse, PrivateKey, type ProMembersResponse, type ProducerReward, type Profile, type ProfileTokens, type PromotePayload, type PromotePrice, type Proposal, type ProposalCreatePayload, type ProposalPay, type ProposalVote, type ProposalVotePayload, type ProposalVoteRow, PublicKey, QUEST_CATALOG, QUEST_MIN_CONTENT_LENGTH, QueryKeys, type QuestCatalogEntry, type QuestMilestone, type QuestPeriod, type QuestStreak, type QuestTier, type QuestsResponse, type RCAccount, ROLES, type RcDelegationActive, type RcDelegationPayload, type RcDirectDelegation, type RcDirectDelegationsResponse, type RcPrecheckInput, type RcPrecheckOperation, type RcPrecheckResult, type RcStats, type Reblog, type ReblogPayload, type ReceivedVestingShare, type RecordActivityOptions, type Recoveries, type RecurrentTransfer, type RecurrentTransfers, type ReferralItem, type ReferralItems, type ReferralStat, ResilienceOptions, type ReturnVestingDelegation, type RewardFund, type RewardedCommunity, SERVER_GC_TIME_MS, SIMILAR_ENTRIES_MIN_RENDER, type SMTAsset, STREAK_FREEZE_MAX_OWNED, STREAK_FREEZE_PRICE, SUBSCRIBERS_PAGE_SIZE, type SavingsWithdrawRequest, type Schedule, SearchQuery, type SearchQueryParts, type SearchResponse, type SearchResult, SearchType, type SetCommunityRolePayload, type SetLastReadPayload, type SetWithdrawRoute, type SetWithdrawVestingRoutePayload, type ShortVideo, type ShortsFeedEntry, type ShortsFeedParams, SortOrder, type Spotlight, type StakeEngineTokenPayload, type StatsResponse, type StreakFreezeBuyResult, type SubscribeCommunityPayload, type Subscription, type SupportSettings, Symbol, THREESPEAK_BENEFICIARY_ACCOUNT, THREESPEAK_BENEFICIARY_WEIGHT, type ThreadItemEntry, type ThreeSpeakBeneficiaryRoute, ThreeSpeakIntegration, type ThreeSpeakVideo, type Token, type TokenMetadata, type Transaction, type TransactionConfirmation, type Transfer, type TransferEngineTokenPayload, type TransferFromSavings, type TransferFromSavingsPayload, type TransferPayload, type TransferPointPayload, type TransferToSavings, type TransferToSavingsPayload, type TransferToVesting, type TransferToVestingPayload, type TrendingTag, type UndelegateEngineTokenPayload, type UnfollowPayload, type UnstakeEngineTokenPayload, type UnsubscribeCommunityPayload, type UpdateCommunityPayload, type UpdateProposalVotes, type UpdateReplyPayload, type UpdateSupportSettingsPayload, type User, type UserImage, type ValidatePostCreatingOptions, type VestingDelegationExpiration, type Vote, type VoteHistoryPage, type VoteHistoryPageParam, type VotePayload, type VoteProxy, type WalletMetadataCandidate, type WalletOperationPayload, type WaveEntry, type WaveTrendingAuthor, type WaveTrendingTag, type WavesFeedEntry, type WavesFeedParams, type WithdrawRoute, type WithdrawVesting, type WithdrawVestingPayload, type Witness, type WitnessProxyPayload, type WitnessVotePayload, type WitnessVoter, type WitnessVoterSortDirection, type WitnessVoterSortField, type WitnessVotersResponse, type WrappedResponse, type WsBookmarkNotification, type WsDelegationsNotification, type WsFavoriteNotification, type WsFollowNotification, type WsInactiveNotification, type WsMentionNotification, type WsNotification, type WsPayoutsNotification, type WsReblogNotification, type WsReferralNotification, type WsReplyNotification, type WsSpinNotification, type WsTransferNotification, type WsVoteNotification, accountNameByteLength, addDraft, addImage, addOptimisticDiscussionEntry, addSchedule, applySupportSettingsUpdate, applyVoteCacheUpdate, bridgeApiCall, broadcastJson, broadcastOperations, broadcastOperationsAsync, buildAccountCreateOp, buildAccountUpdate2Op, buildAccountUpdateOp, buildActiveCustomJsonOp, buildBoostPlusOp, buildCancelTransferFromSavingsOp, buildChangeRecoveryAccountOp, buildClaimAccountOp, buildClaimInterestOps, buildClaimRewardBalanceOp, buildCollateralizedConvertOp, buildCommentOp, buildCommentOptionsOp, buildCommunityRegistrationOp, buildConvertOp, buildCreateClaimedAccountOp, buildDelegateRcOp, buildDelegateVestingSharesOp, buildDeleteCommentOp, buildEngineClaimOp, buildEngineOp, buildFlagPostOp, buildFollowOp, buildGrantPostingPermissionOp, buildIgnoreOp, buildLimitOrderCancelOp, buildLimitOrderCreateOp, buildLimitOrderCreateOpWithType, buildMultiPointTransferOps, buildMultiTransferOps, buildMutePostOp, buildMuteUserOp, buildPinPostOp, buildPointTransferOp, buildPostingCustomJsonOp, buildPostingJsonMetadata, buildProfileMetadata, buildPromoteOp, buildProposalCreateOp, buildProposalVoteOp, buildRcDelegationOp, buildReblogOp, buildRecoverAccountOp, buildRecurrentTransferOp, buildRemoveProposalOp, buildRequestAccountRecoveryOp, buildRevokeKeysOp, buildRevokePostingPermissionOp, buildSearchQuery, buildSetLastReadOps, buildSetRoleOp, buildSetWithdrawVestingRouteOp, buildSubscribeOp, buildTransferFromSavingsOp, buildTransferOp, buildTransferToSavingsOp, buildTransferToVestingOp, buildUnfollowOp, buildUnignoreOp, buildUnsubscribeOp, buildUpdateCommunityOp, buildUpdateProposalOp, buildVoteOp, buildWithdrawVestingOp, buildWitnessProxyOp, buildWitnessVoteOp, buyStreakFreezeRequest, calculateRCMana, calculateVPMana, canRevokeFromAuthority, checkFavoriteQueryOptions, checkUsernameWalletsPendingQueryOptions, claimPointsRequest, collectRequestedOperations, decodeObj, dedupeAndSortKeyAuths, deleteDraft, deleteImage, deleteSchedule, downVotingPower, earnsQuestContentCredit, encodeObj, enforceThreeSpeakBeneficiary, estimateRcPrecheck, extractAccountProfile, formatError, formattedNumber, getAccountDelegationsQueryOptions, getAccountFullQueryOptions, getAccountNotificationsInfiniteQueryOptions, getAccountPendingRecoveryQueryOptions, getAccountPosts, getAccountPostsInfiniteQueryOptions, getAccountPostsQueryOptions, getAccountRcQueryOptions, getAccountRecoveriesQueryOptions, getAccountReputationsQueryOptions, getAccountSubscriptionsQueryOptions, getAccountVoteHistoryInfiniteQueryOptions, getAccountWalletAssetInfoQueryOptions, getAccountsQueryOptions, getAggregatedBalanceQueryOptions, getAiAssistPriceQueryOptions, getAiGeneratePriceQueryOptions, getAiTranscribePriceQueryOptions, getAllHiveEngineTokensQueryOptions, getAnnouncementsQueryOptions, getBadActorsQueryOptions, getBalanceHistoryInfiniteQueryOptions, getBookmarksInfiniteQueryOptions, getBookmarksQueryOptions, getBoostPlusAccountPricesQueryOptions, getBoostPlusPricesQueryOptions, getBotsQueryOptions, getBoundFetch, getChainPropertiesQueryOptions, getCollateralizedConversionRequestsQueryOptions, getCommentHistoryQueryOptions, getCommunities, getCommunitiesQueryOptions, getCommunity, getCommunityContextQueryOptions, getCommunityPermissions, getCommunityQueryOptions, getCommunitySubscribersInfiniteQueryOptions, getCommunitySubscribersQueryOptions, getCommunityType, getContentQueryOptions, getContentRepliesQueryOptions, getControversialRisingInfiniteQueryOptions, getConversionRequestsQueryOptions, getCurrencyRate, getCurrencyRates, getCurrencyTokenRate, getCurrentMedianHistoryPriceQueryOptions, getCustomJsonAuthority, getDeletedEntryQueryOptions, getDiscoverCurationQueryOptions, getDiscoverLeaderboardQueryOptions, getDiscussion, getDiscussionQueryOptions, getDiscussionsQueryOptions, getDraftsInfiniteQueryOptions, getDraftsQueryOptions, getDynamicPropsQueryOptions, getEntryActiveVotesQueryOptions, getFavoritesInfiniteQueryOptions, getFavoritesQueryOptions, getFeedHistoryQueryOptions, getFollowCountQueryOptions, getFollowersQueryOptions, getFollowingQueryOptions, getFragmentsInfiniteQueryOptions, getFragmentsQueryOptions, getFriendsInfiniteQueryOptions, getGalleryImagesQueryOptions, getGameStatusCheckQueryOptions, getHbdAssetGeneralInfoQueryOptions, getHbdAssetTransactionsQueryOptions, getHiveAssetGeneralInfoQueryOptions, getHiveAssetMetricQueryOptions, getHiveAssetTransactionsQueryOptions, getHiveAssetWithdrawalRoutesQueryOptions, getHiveEngineBalancesWithUsdQueryOptions, getHiveEngineMetrics, getHiveEngineOpenOrders, getHiveEngineOrderBook, getHiveEngineTokenGeneralInfoQueryOptions, getHiveEngineTokenMetrics, getHiveEngineTokenTransactions, getHiveEngineTokenTransactionsQueryOptions, getHiveEngineTokensBalances, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMarket, getHiveEngineTokensMarketQueryOptions, getHiveEngineTokensMetadata, getHiveEngineTokensMetadataQueryOptions, getHiveEngineTokensMetricsQueryOptions, getHiveEngineTradeHistory, getHiveEngineUnclaimedRewards, getHiveEngineUnclaimedRewardsQueryOptions, getHiveHbdStatsQueryOptions, getHivePoshLinksQueryOptions, getHivePowerAssetGeneralInfoQueryOptions, getHivePowerAssetTransactionsQueryOptions, getHivePowerDelegatesInfiniteQueryOptions, getHivePowerDelegatingsQueryOptions, getHivePrice, getImagesInfiniteQueryOptions, getImagesQueryOptions, getIncomingRcQueryOptions, getMarketData, getMarketDataQueryOptions, getMarketHistoryQueryOptions, getMarketStatisticsQueryOptions, getMutedUsersQueryOptions, getNextAccountHistoryPageParam, getNormalizePostQueryOptions, getNotificationSetting, getNotifications, getNotificationsInfiniteQueryOptions, getNotificationsSettingsQueryOptions, getNotificationsUnreadCountQueryOptions, getOpenOrdersQueryOptions, getOperationAuthority, getOrderBookQueryOptions, getOutgoingRcDelegationsInfiniteQueryOptions, getPageStatsQueryOptions, getPointsAssetGeneralInfoQueryOptions, getPointsAssetTransactionsQueryOptions, getPointsQueryOptions, getPollQueryOptions, getPortfolioQueryOptions, getPost, getPostHeader, getPostHeaderQueryOptions, getPostQueryOptions, getPostTipsQueryOptions, getPostsRanked, getPostsRankedInfiniteQueryOptions, getPostsRankedQueryOptions, getProMembersQueryOptions, getProfiles, getProfilesQueryOptions, getPromotePriceQueryOptions, getPromotedPost, getPromotedPostsQuery, getProposalAuthority, getProposalQueryOptions, getProposalVotesInfiniteQueryOptions, getProposalsQueryOptions, getQueryClient, getQuestCatalogEntry, getQuestsQueryOptions, getRcDelegationActiveQueryOptions, getRcDelegationPricesQueryOptions, getRcStatsQueryOptions, getRebloggedByQueryOptions, getReblogsQueryOptions, getReceivedVestingSharesQueryOptions, getRecurrentTransfersQueryOptions, getReferralsInfiniteQueryOptions, getReferralsStatsQueryOptions, getRelationshipBetweenAccounts, getRelationshipBetweenAccountsQueryOptions, getRequiredAuthority, getRewardFundQueryOptions, getRewardedCommunitiesQueryOptions, getSavingsWithdrawFromQueryOptions, getSchedulesInfiniteQueryOptions, getSchedulesQueryOptions, getSearchAccountQueryOptions, getSearchAccountsByUsernameQueryOptions, getSearchApiInfiniteQueryOptions, getSearchFriendsQueryOptions, getSearchPathQueryOptions, getSearchTopicsQueryOptions, getShortsFeedQueryOptions, getSimilarEntriesQueryOptions, getSpotlightsQueryOptions, getStatsQueryOptions, getSubscribers, getSubscriptions, getSupportSettingsQueryOptions, getSupportSettingsRequest, getTradeHistoryQueryOptions, getTransactionsInfiniteQueryOptions, getTrendingTagsQueryOptions, getTrendingTagsWithStatsQueryOptions, getUserPostVoteQueryOptions, getUserProposalVotesQueryOptions, getVestingDelegationExpirationsQueryOptions, getVestingDelegationsQueryOptions, getVisibleFirstLevelThreadItems, getWavesByAccountQueryOptions, getWavesByHostQueryOptions, getWavesByTagQueryOptions, getWavesFeedQueryOptions, getWavesFollowingQueryOptions, getWavesLatestFeedQueryOptions, getWavesTrendingAuthorsQueryOptions, getWavesTrendingTagsQueryOptions, getWithdrawRoutesQueryOptions, getWitnessVoterCountQueryOptions, getWitnessVotersPageQueryOptions, getWitnessesInfiniteQueryOptions, hasThreeSpeakEmbed, hsTokenRenew, invalidateAfterBroadcast, isCommunity, isEmptyDate, isInfoError, isNetworkError, isQueryableAccountName, isResourceCreditsError, isThreeSpeakBeneficiary, isVoteAlreadyReflected, isWif, isWrappedResponse, lookupAccountsQueryOptions, makeQueryClient, mapMetaChoicesToPollChoices, mapThreadItemsToWaveEntries, markNotifications, measureQuestContentLength, moveSchedule, normalizePost, normalizeSearchAuthor, normalizeSearchCategory, normalizeSearchTags, normalizeToWrappedResponse, normalizeWaveEntryFromApi, onboardEmail, parseAccounts, parseAsset, parseChainError, parsePostingMetadataRoot, parseProfileMetadata, pickRicherMetadataSnapshot, powerRechargeTime, proMembersSet, rcPower, removeOptimisticDiscussionEntry, resolveAccountHistoryLimit, resolveHiveOperationFilters, resolvePost, restoreDiscussionSnapshots, restoreEntryInCache, roleMap, saveNotificationSetting, search, searchPath, searchQueryOptions, sha256, shouldTriggerAuthFallback, signUp, similar, sortDiscussions, subscribeEmail, toEntryArray, updateDraft, updateEntryInCache, updateSupportSettingsRequest, uploadImage, uploadImageWithSignature, useAccountFavoriteAdd, useAccountFavoriteDelete, useAccountRelationsUpdate, useAccountRevokeKey, useAccountRevokePosting, useAccountUpdate, useAccountUpdateKeyAuths, useAccountUpdatePassword, useAccountUpdateRecovery, useAddDraft, useAddFragment, useAddImage, useAddSchedule, useAiAssist, useAiTranscribe, useBookmarkAdd, useBookmarkDelete, useBoostPlus, useBroadcastMutation, useBuyStreakFreeze, useClaimAccount, useClaimEngineRewards, useClaimInterest, useClaimPoints, useClaimRewards, useComment, useConvert, useCreateAccount, useCrossPost, useDelegateEngineToken, useDelegateRc, useDelegateVestingShares, useDeleteComment, useDeleteDraft, useDeleteImage, useDeleteSchedule, useEditFragment, useEngineMarketOrder, useFollow, useGameClaim, useGenerateImage, useGrantPostingPermission, useLimitOrderCancel, useLimitOrderCreate, useMarkNotificationsRead, useMoveSchedule, useMutePost, usePinPost, usePollVote, usePromote, useProposalCreate, useProposalVote, useRcDelegation, useReblog, useRecordActivity, useRegisterCommunityRewards, useRemoveFragment, useSetCommunityRole, useSetLastRead, useSetWithdrawVestingRoute, useSignOperationByHivesigner, useSignOperationByKey, useSignOperationByKeychain, useStakeEngineToken, useSubscribeCommunity, useTransfer, useTransferEngineToken, useTransferFromSavings, useTransferPoint, useTransferToSavings, useTransferToVesting, useUndelegateEngineToken, useUnfollow, useUnstakeEngineToken, useUnsubscribeCommunity, useUpdateCommunity, useUpdateDraft, useUpdateReply, useUpdateSupportSettings, useUploadImage, useVote, useWalletOperation, useWithdrawVesting, useWitnessProxy, useWitnessVote, usrActivity, validatePostCreating, verifyPostOnAlternateNode, vestsToHp, votingPower, votingRshares, votingValue, withTimeoutSignal }; +export { ACCOUNT_OPERATION_GROUPS, ALL_ACCOUNT_OPERATIONS, ALL_NOTIFY_TYPES, type AccountBookmark, type AccountDelegations, type AccountFavorite, type AccountFollowStats, type AccountKeys, type AccountNotification, type AccountProfile, type AccountRelationship, type AccountReputation, type AggregatedBalanceEntry, type AiAssistParams, type AiAssistPrice, type AiAssistResponse, type AiGenerationPrice, type AiGenerationRequest, type AiGenerationResponse, type AiImagePowerTier, type AiImagePriceResponse, type AiTranscribeParams, type AiTranscribePrice, type AiTranscribeResponse, type Announcement, type ApiBookmarkNotification, type ApiDelegationsNotification, type ApiFavoriteNotification, type ApiFollowNotification, type ApiInactiveNotification, type ApiMentionNotification, type ApiNotification, type ApiNotificationSetting, type ApiPayoutsNotification, type ApiReblogNotification, type ApiReferralNotification, type ApiReplyNotification, type ApiResponse, type ApiScheduledPublishedNotification, type ApiSpinNotification, type ApiTransferNotification, type ApiVoteNotification, type ApiWeeklyEarningsNotification, type Asset, AssetOperation, type AuthContext, type AuthContextV2, type AuthMethod, type AuthorReward, Authority, type AuthorityLevel, type AuthorityType, BROADCAST_INCLUSION_DELAY_MS, type BalanceAggregationGranularity, type BalanceCoinType, type BalanceHistoryEntry, type BalanceHistoryResponse, type Beneficiary, type BeneficiaryRoute, type BlogEntry, type BoostPlusAccountPrice, type BoostPlusPayload, type BroadcastMode, BroadcastResult, type BuildProfileMetadataArgs, type BuiltSearchQuery, BuySellTransactionType, CONFIG, type CancelTransferFromSavings, type CantAfford, type CheckUsernameWalletsPendingResponse, type ClaimAccountPayload, type ClaimEngineRewardsPayload, type ClaimInterestPayload, type ClaimRewardBalance, type ClaimRewardsPayload, type CollateralizedConversionRequest, type CollateralizedConvert, type CommentBenefactor, type CommentLike, type CommentOptionsLike, type CommentPayload, type CommentPayoutUpdate, type CommentRcCostEstimate, type CommentResourceUsageInput, type CommentReward, type CommentTransactionInput, type Communities, type Community, type CommunityProps, type CommunityRewardsRegisterPayload, type CommunityRole, type CommunityTeam, type CommunityType, ConfigManager, type ConversionRequest, type ConvertPayload, type CreateAccountPayload, type CrossPostPayload, type CurationDuration, type CurationItem, type CurationReward, type CurrencyRates, type DailyCheckinQuest, type DailyContentQuest, type DailyQuest, type DelegateEngineTokenPayload, type DelegateRcPayload, type DelegateVestingShares, type DelegateVestingSharesPayload, type DelegatedVestingShare, type DeleteCommentPayload, type DeletedEntry, type Draft, type DraftMetadata, type DraftRewardType, type DraftsWrappedResponse, type DynamicProps$1 as DynamicProps, index as EcencyAnalytics, EcencyQueriesManager, type EffectiveCommentVote, type EngineMarketOrderPayload, EntriesCacheManagement, type Entry$1 as Entry, type EntryBeneficiaryRoute, type EntryHeader, type EntryStat, type EntryVote, ErrorType, type EstimateCommentRcCostInput, type FeedHistoryItem, type FillCollateralizedConvertRequest, type FillConvertRequest, type FillOrder, type FillRecurrentTransfers, type FillTransferFromSavings, type FillVestingWithdraw, type Follow, type FollowPayload, type Fragment, type FriendSearchResult, type FriendsPageParam, type FriendsRow, type FullAccount, type GameClaim, type GeneralAssetInfo, type GeneralAssetTransaction, type GenerateImageParams, type GetGameStatus, type GetRecoveriesEmailResponse, type GrantPostingPermissionPayload, HIVE_ACCOUNT_OPERATION_GROUPS, HIVE_OPERATION_LIST, HIVE_OPERATION_NAME_BY_ID, HIVE_OPERATION_ORDERS, type HiveBasedAssetSignType, type HiveEngineMarketResponse, type HiveEngineMetric, type HiveEngineOpenOrder, type HiveEngineOrderBookEntry, HiveEngineToken, type HiveEngineTokenBalance, type HiveEngineTokenInfo, type HiveEngineTokenMetadataResponse, type HiveEngineTokenStatus, type HiveEngineTransaction, type HiveHbdStats, type HiveMarketMetric, type HiveOperationFilter, type HiveOperationFilterKey, type HiveOperationFilterValue, type HiveOperationGroup, type HiveOperationName, HiveSignerIntegration, type HiveTransaction, type HsTokenRenewResponse, INTERNAL_API_TIMEOUT_MS, type IncomingDelegation, type IncomingRcDelegation, type IncomingRcResponse, type Interest, type JsonMetadata, type JsonPollMetadata, type Keys, type LeaderBoardDuration, type LeaderBoardItem, type LimitOrderCancel, type LimitOrderCancelPayload, type LimitOrderCreate, type LimitOrderCreatePayload, MAX_SEARCH_QUERY_LENGTH, MAX_SEARCH_TAGS, type MarketCandlestickDataItem, type MarketData, type MarketStatistics, type MedianHistoryPrice, type MutePostPayload, NaiMap, NotificationFilter, NotificationViewType, type Notifications, NotifyTypes, OPERATION_AUTHORITY_MAP, type OpenOrdersData, Operation, type OperationGroup, OperationName, OrderIdPrefix, type OrdersData, type OrdersDataItem, type OutgoingDelegation, POLLS_PROTOCOL_VERSION, type PageStatsResponse, type PaginationMeta, type ParsedChainError, type Payer, type PeriodQuest, type PinPostPayload, type PlatformAdapter, type PointTransaction, PointTransactionType, type Points, type PointsResponse, type Poll, type PollChoice, type PollChoiceVotes, PollPreferredInterpretation, type PollStats, type PollVotePayload, type PollVoter, type PortfolioResponse, type PortfolioWalletItem, type PostTip, type PostTipsResponse, PrivateKey, type ProMembersResponse, type ProducerReward, type Profile, type ProfileTokens, type PromotePayload, type PromotePrice, type Proposal, type ProposalCreatePayload, type ProposalPay, type ProposalVote, type ProposalVotePayload, type ProposalVoteRow, PublicKey, QUEST_CATALOG, QUEST_MIN_CONTENT_LENGTH, QueryKeys, type QuestCatalogEntry, type QuestMilestone, type QuestPeriod, type QuestStreak, type QuestTier, type QuestsResponse, type RCAccount, RC_RESOURCE_NAMES, ROLES, type RcCostBreakdown, type RcDelegationActive, type RcDelegationPayload, type RcDirectDelegation, type RcDirectDelegationsResponse, type RcPrecheckInput, type RcPrecheckOperation, type RcPrecheckResult, type RcPriceCurveParams, type RcResourceDynamicsParams, type RcResourceName, type RcResourceParamEntry, type RcResourceParams, type RcSizeInfo, type RcStats, type Reblog, type ReblogPayload, type ReceivedVestingShare, type RecordActivityOptions, type Recoveries, type RecurrentTransfer, type RecurrentTransfers, type ReferralItem, type ReferralItems, type ReferralStat, ResilienceOptions, type ReturnVestingDelegation, type RewardFund, type RewardedCommunity, SERVER_GC_TIME_MS, SIMILAR_ENTRIES_MIN_RENDER, type SMTAsset, STREAK_FREEZE_MAX_OWNED, STREAK_FREEZE_PRICE, SUBSCRIBERS_PAGE_SIZE, type SavingsWithdrawRequest, type Schedule, SearchQuery, type SearchQueryParts, type SearchResponse, type SearchResult, SearchType, type SetCommunityRolePayload, type SetLastReadPayload, type SetWithdrawRoute, type SetWithdrawVestingRoutePayload, type ShortVideo, type ShortsFeedEntry, type ShortsFeedParams, SortOrder, type Spotlight, type StakeEngineTokenPayload, type StatsResponse, type StreakFreezeBuyResult, type SubscribeCommunityPayload, type Subscription, type SupportSettings, Symbol, THREESPEAK_BENEFICIARY_ACCOUNT, THREESPEAK_BENEFICIARY_WEIGHT, type ThreadItemEntry, type ThreeSpeakBeneficiaryRoute, ThreeSpeakIntegration, type ThreeSpeakVideo, type Token, type TokenMetadata, type Transaction, type TransactionConfirmation, type Transfer, type TransferEngineTokenPayload, type TransferFromSavings, type TransferFromSavingsPayload, type TransferPayload, type TransferPointPayload, type TransferToSavings, type TransferToSavingsPayload, type TransferToVesting, type TransferToVestingPayload, type TrendingTag, type UndelegateEngineTokenPayload, type UnfollowPayload, type UnstakeEngineTokenPayload, type UnsubscribeCommunityPayload, type UpdateCommunityPayload, type UpdateProposalVotes, type UpdateReplyPayload, type UpdateSupportSettingsPayload, type User, type UserImage, type ValidatePostCreatingOptions, type VestingDelegationExpiration, type Vote, type VoteHistoryPage, type VoteHistoryPageParam, type VotePayload, type VoteProxy, type WalletMetadataCandidate, type WalletOperationPayload, type WaveEntry, type WaveTrendingAuthor, type WaveTrendingTag, type WavesFeedEntry, type WavesFeedParams, type WithdrawRoute, type WithdrawVesting, type WithdrawVestingPayload, type Witness, type WitnessProxyPayload, type WitnessVotePayload, type WitnessVoter, type WitnessVoterSortDirection, type WitnessVoterSortField, type WitnessVotersResponse, type WrappedResponse, type WsBookmarkNotification, type WsDelegationsNotification, type WsFavoriteNotification, type WsFollowNotification, type WsInactiveNotification, type WsMentionNotification, type WsNotification, type WsPayoutsNotification, type WsReblogNotification, type WsReferralNotification, type WsReplyNotification, type WsSpinNotification, type WsTransferNotification, type WsVoteNotification, accountNameByteLength, addDraft, addImage, addOptimisticDiscussionEntry, addSchedule, applySupportSettingsUpdate, applyVoteCacheUpdate, bridgeApiCall, broadcastJson, broadcastOperations, broadcastOperationsAsync, buildAccountCreateOp, buildAccountUpdate2Op, buildAccountUpdateOp, buildActiveCustomJsonOp, buildBoostPlusOp, buildCancelTransferFromSavingsOp, buildChangeRecoveryAccountOp, buildClaimAccountOp, buildClaimInterestOps, buildClaimRewardBalanceOp, buildCollateralizedConvertOp, buildCommentOp, buildCommentOptionsOp, buildCommunityRegistrationOp, buildConvertOp, buildCreateClaimedAccountOp, buildDelegateRcOp, buildDelegateVestingSharesOp, buildDeleteCommentOp, buildEngineClaimOp, buildEngineOp, buildFlagPostOp, buildFollowOp, buildGrantPostingPermissionOp, buildIgnoreOp, buildLimitOrderCancelOp, buildLimitOrderCreateOp, buildLimitOrderCreateOpWithType, buildMultiPointTransferOps, buildMultiTransferOps, buildMutePostOp, buildMuteUserOp, buildPinPostOp, buildPointTransferOp, buildPostingCustomJsonOp, buildPostingJsonMetadata, buildProfileMetadata, buildPromoteOp, buildProposalCreateOp, buildProposalVoteOp, buildRcDelegationOp, buildReblogOp, buildRecoverAccountOp, buildRecurrentTransferOp, buildRemoveProposalOp, buildRequestAccountRecoveryOp, buildRevokeKeysOp, buildRevokePostingPermissionOp, buildSearchQuery, buildSetLastReadOps, buildSetRoleOp, buildSetWithdrawVestingRouteOp, buildSubscribeOp, buildTransferFromSavingsOp, buildTransferOp, buildTransferToSavingsOp, buildTransferToVestingOp, buildUnfollowOp, buildUnignoreOp, buildUnsubscribeOp, buildUpdateCommunityOp, buildUpdateProposalOp, buildVoteOp, buildWithdrawVestingOp, buildWitnessProxyOp, buildWitnessVoteOp, buyStreakFreezeRequest, calculateRCMana, calculateVPMana, canRevokeFromAuthority, checkFavoriteQueryOptions, checkUsernameWalletsPendingQueryOptions, claimPointsRequest, collectRequestedOperations, computeResourceCost, countCommentResourceUsage, decodeObj, dedupeAndSortKeyAuths, deleteDraft, deleteImage, deleteSchedule, downVotingPower, earnsQuestContentCredit, encodeObj, enforceThreeSpeakBeneficiary, estimateCommentRcCost, estimateCommentTransactionBytes, estimateRcPrecheck, extractAccountProfile, formatError, formattedNumber, getAccountDelegationsQueryOptions, getAccountFullQueryOptions, getAccountNotificationsInfiniteQueryOptions, getAccountPendingRecoveryQueryOptions, getAccountPosts, getAccountPostsInfiniteQueryOptions, getAccountPostsQueryOptions, getAccountRcQueryOptions, getAccountRecoveriesQueryOptions, getAccountReputationsQueryOptions, getAccountSubscriptionsQueryOptions, getAccountVoteHistoryInfiniteQueryOptions, getAccountWalletAssetInfoQueryOptions, getAccountsQueryOptions, getAggregatedBalanceQueryOptions, getAiAssistPriceQueryOptions, getAiGeneratePriceQueryOptions, getAiTranscribePriceQueryOptions, getAllHiveEngineTokensQueryOptions, getAnnouncementsQueryOptions, getBadActorsQueryOptions, getBalanceHistoryInfiniteQueryOptions, getBookmarksInfiniteQueryOptions, getBookmarksQueryOptions, getBoostPlusAccountPricesQueryOptions, getBoostPlusPricesQueryOptions, getBotsQueryOptions, getBoundFetch, getChainPropertiesQueryOptions, getCollateralizedConversionRequestsQueryOptions, getCommentHistoryQueryOptions, getCommunities, getCommunitiesQueryOptions, getCommunity, getCommunityContextQueryOptions, getCommunityPermissions, getCommunityQueryOptions, getCommunitySubscribersInfiniteQueryOptions, getCommunitySubscribersQueryOptions, getCommunityType, getContentQueryOptions, getContentRepliesQueryOptions, getControversialRisingInfiniteQueryOptions, getConversionRequestsQueryOptions, getCurrencyRate, getCurrencyRates, getCurrencyTokenRate, getCurrentMedianHistoryPriceQueryOptions, getCustomJsonAuthority, getDeletedEntryQueryOptions, getDiscoverCurationQueryOptions, getDiscoverLeaderboardQueryOptions, getDiscussion, getDiscussionQueryOptions, getDiscussionsQueryOptions, getDraftsInfiniteQueryOptions, getDraftsQueryOptions, getDynamicPropsQueryOptions, getEntryActiveVotesQueryOptions, getFavoritesInfiniteQueryOptions, getFavoritesQueryOptions, getFeedHistoryQueryOptions, getFollowCountQueryOptions, getFollowersQueryOptions, getFollowingQueryOptions, getFragmentsInfiniteQueryOptions, getFragmentsQueryOptions, getFriendsInfiniteQueryOptions, getGalleryImagesQueryOptions, getGameStatusCheckQueryOptions, getHbdAssetGeneralInfoQueryOptions, getHbdAssetTransactionsQueryOptions, getHiveAssetGeneralInfoQueryOptions, getHiveAssetMetricQueryOptions, getHiveAssetTransactionsQueryOptions, getHiveAssetWithdrawalRoutesQueryOptions, getHiveEngineBalancesWithUsdQueryOptions, getHiveEngineMetrics, getHiveEngineOpenOrders, getHiveEngineOrderBook, getHiveEngineTokenGeneralInfoQueryOptions, getHiveEngineTokenMetrics, getHiveEngineTokenTransactions, getHiveEngineTokenTransactionsQueryOptions, getHiveEngineTokensBalances, getHiveEngineTokensBalancesQueryOptions, getHiveEngineTokensMarket, getHiveEngineTokensMarketQueryOptions, getHiveEngineTokensMetadata, getHiveEngineTokensMetadataQueryOptions, getHiveEngineTokensMetricsQueryOptions, getHiveEngineTradeHistory, getHiveEngineUnclaimedRewards, getHiveEngineUnclaimedRewardsQueryOptions, getHiveHbdStatsQueryOptions, getHivePoshLinksQueryOptions, getHivePowerAssetGeneralInfoQueryOptions, getHivePowerAssetTransactionsQueryOptions, getHivePowerDelegatesInfiniteQueryOptions, getHivePowerDelegatingsQueryOptions, getHivePrice, getImagesInfiniteQueryOptions, getImagesQueryOptions, getIncomingRcQueryOptions, getMarketData, getMarketDataQueryOptions, getMarketHistoryQueryOptions, getMarketStatisticsQueryOptions, getMutedUsersQueryOptions, getNextAccountHistoryPageParam, getNormalizePostQueryOptions, getNotificationSetting, getNotifications, getNotificationsInfiniteQueryOptions, getNotificationsSettingsQueryOptions, getNotificationsUnreadCountQueryOptions, getOpenOrdersQueryOptions, getOperationAuthority, getOrderBookQueryOptions, getOutgoingRcDelegationsInfiniteQueryOptions, getPageStatsQueryOptions, getPointsAssetGeneralInfoQueryOptions, getPointsAssetTransactionsQueryOptions, getPointsQueryOptions, getPollQueryOptions, getPortfolioQueryOptions, getPost, getPostHeader, getPostHeaderQueryOptions, getPostQueryOptions, getPostTipsQueryOptions, getPostsRanked, getPostsRankedInfiniteQueryOptions, getPostsRankedQueryOptions, getProMembersQueryOptions, getProfiles, getProfilesQueryOptions, getPromotePriceQueryOptions, getPromotedPost, getPromotedPostsQuery, getProposalAuthority, getProposalQueryOptions, getProposalVotesInfiniteQueryOptions, getProposalsQueryOptions, getQueryClient, getQuestCatalogEntry, getQuestsQueryOptions, getRcDelegationActiveQueryOptions, getRcDelegationPricesQueryOptions, getRcResourceParamsQueryOptions, getRcStatsQueryOptions, getRebloggedByQueryOptions, getReblogsQueryOptions, getReceivedVestingSharesQueryOptions, getRecurrentTransfersQueryOptions, getReferralsInfiniteQueryOptions, getReferralsStatsQueryOptions, getRelationshipBetweenAccounts, getRelationshipBetweenAccountsQueryOptions, getRequiredAuthority, getRewardFundQueryOptions, getRewardedCommunitiesQueryOptions, getSavingsWithdrawFromQueryOptions, getSchedulesInfiniteQueryOptions, getSchedulesQueryOptions, getSearchAccountQueryOptions, getSearchAccountsByUsernameQueryOptions, getSearchApiInfiniteQueryOptions, getSearchFriendsQueryOptions, getSearchPathQueryOptions, getSearchTopicsQueryOptions, getShortsFeedQueryOptions, getSimilarEntriesQueryOptions, getSpotlightsQueryOptions, getStatsQueryOptions, getSubscribers, getSubscriptions, getSupportSettingsQueryOptions, getSupportSettingsRequest, getTradeHistoryQueryOptions, getTransactionsInfiniteQueryOptions, getTrendingTagsQueryOptions, getTrendingTagsWithStatsQueryOptions, getUserPostVoteQueryOptions, getUserProposalVotesQueryOptions, getVestingDelegationExpirationsQueryOptions, getVestingDelegationsQueryOptions, getVisibleFirstLevelThreadItems, getWavesByAccountQueryOptions, getWavesByHostQueryOptions, getWavesByTagQueryOptions, getWavesFeedQueryOptions, getWavesFollowingQueryOptions, getWavesLatestFeedQueryOptions, getWavesTrendingAuthorsQueryOptions, getWavesTrendingTagsQueryOptions, getWithdrawRoutesQueryOptions, getWitnessVoterCountQueryOptions, getWitnessVotersPageQueryOptions, getWitnessesInfiniteQueryOptions, hasThreeSpeakEmbed, hsTokenRenew, invalidateAfterBroadcast, isCommunity, isEmptyDate, isInfoError, isNetworkError, isQueryableAccountName, isResourceCreditsError, isThreeSpeakBeneficiary, isVoteAlreadyReflected, isWif, isWrappedResponse, lookupAccountsQueryOptions, makeQueryClient, mapMetaChoicesToPollChoices, mapThreadItemsToWaveEntries, markNotifications, measureQuestContentLength, moveSchedule, normalizePost, normalizeSearchAuthor, normalizeSearchCategory, normalizeSearchTags, normalizeToWrappedResponse, normalizeWaveEntryFromApi, onboardEmail, parseAccounts, parseAsset, parseChainError, parsePostingMetadataRoot, parseProfileMetadata, pickRicherMetadataSnapshot, powerRechargeTime, proMembersSet, rcPower, removeOptimisticDiscussionEntry, resolveAccountHistoryLimit, resolveHiveOperationFilters, resolvePost, restoreDiscussionSnapshots, restoreEntryInCache, roleMap, saveNotificationSetting, search, searchPath, searchQueryOptions, sha256, shouldTriggerAuthFallback, signUp, similar, sortDiscussions, subscribeEmail, toEntryArray, updateDraft, updateEntryInCache, updateSupportSettingsRequest, uploadImage, uploadImageWithSignature, useAccountFavoriteAdd, useAccountFavoriteDelete, useAccountRelationsUpdate, useAccountRevokeKey, useAccountRevokePosting, useAccountUpdate, useAccountUpdateKeyAuths, useAccountUpdatePassword, useAccountUpdateRecovery, useAddDraft, useAddFragment, useAddImage, useAddSchedule, useAiAssist, useAiTranscribe, useBookmarkAdd, useBookmarkDelete, useBoostPlus, useBroadcastMutation, useBuyStreakFreeze, useClaimAccount, useClaimEngineRewards, useClaimInterest, useClaimPoints, useClaimRewards, useComment, useConvert, useCreateAccount, useCrossPost, useDelegateEngineToken, useDelegateRc, useDelegateVestingShares, useDeleteComment, useDeleteDraft, useDeleteImage, useDeleteSchedule, useEditFragment, useEngineMarketOrder, useFollow, useGameClaim, useGenerateImage, useGrantPostingPermission, useLimitOrderCancel, useLimitOrderCreate, useMarkNotificationsRead, useMoveSchedule, useMutePost, usePinPost, usePollVote, usePromote, useProposalCreate, useProposalVote, useRcDelegation, useReblog, useRecordActivity, useRegisterCommunityRewards, useRemoveFragment, useSetCommunityRole, useSetLastRead, useSetWithdrawVestingRoute, useSignOperationByHivesigner, useSignOperationByKey, useSignOperationByKeychain, useStakeEngineToken, useSubscribeCommunity, useTransfer, useTransferEngineToken, useTransferFromSavings, useTransferPoint, useTransferToSavings, useTransferToVesting, useUndelegateEngineToken, useUnfollow, useUnstakeEngineToken, useUnsubscribeCommunity, useUpdateCommunity, useUpdateDraft, useUpdateReply, useUpdateSupportSettings, useUploadImage, useVote, useWalletOperation, useWithdrawVesting, useWitnessProxy, useWitnessVote, usrActivity, utf8ByteLength, validatePostCreating, varintByteLength, verifyPostOnAlternateNode, vestsToHp, votingPower, votingRshares, votingValue, withTimeoutSignal }; diff --git a/packages/sdk/dist/browser/index.js b/packages/sdk/dist/browser/index.js index 388c4e216d..f7db06738c 100644 --- a/packages/sdk/dist/browser/index.js +++ b/packages/sdk/dist/browser/index.js @@ -1,10 +1,10 @@ -import {useQuery,useInfiniteQuery,useMutation,QueryClient,queryOptions,infiniteQueryOptions,useQueryClient,isServer}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import sn from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import Wn from'hivesigner';var Xr=Object.defineProperty;var Eo=(e,t,r)=>t in e?Xr(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var yt=(e,t)=>{for(var r in t)Xr(e,r,{get:t[r],enumerable:true});};var A=(e,t,r)=>Eo(e,typeof t!="symbol"?t+"":t,r);var ht=new ArrayBuffer(0),wt=null,_t=null;function So(){return wt||(typeof TextEncoder<"u"?wt=new TextEncoder:wt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),wt}function Zr(){return _t||(typeof TextDecoder<"u"?_t=new TextDecoder:_t={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),_t}var j=class j{constructor(t=j.DEFAULT_CAPACITY,r=j.DEFAULT_ENDIAN){A(this,"buffer");A(this,"view");A(this,"offset");A(this,"markedOffset");A(this,"limit");A(this,"littleEndian");A(this,"readUInt32",this.readUint32);this.buffer=t===0?ht:new ArrayBuffer(t),this.view=t===0?new DataView(ht):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new j(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new j(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(ht));else if(Array.isArray(t))n=new j(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof j?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new j(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new j(0,this.littleEndian);let n=r-t,i=new j(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?ht:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=So().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=Zr().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=Zr().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};A(j,"LITTLE_ENDIAN",true),A(j,"BIG_ENDIAN",false),A(j,"DEFAULT_CAPACITY",16),A(j,"DEFAULT_ENDIAN",j.BIG_ENDIAN);var D=j;var E={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},Gt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],zt=e=>{let t=Gt(e);t.length&&(E.nodes=t);},Jt=e=>{let t=Gt(e);t.length&&(E.restNodes=t);},Yt=e=>{if(!e||typeof e!="object")return;let t={...E.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=Gt(n);i.length?t[r]=i:delete t[r];}E.restNodesByApi=t;},Xt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(E.userAgent=t);},Zt=e=>{if(!e||typeof e!="object")return;let t=E.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var Oe=class e{constructor(t,r,n){A(this,"data");A(this,"recovery");A(this,"compressed");this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new X(n.recoverPublicKey(t).toBytes())}};var X=class e{constructor(t,r){A(this,"key");A(this,"prefix");this.key=t,this.prefix=r??E.address_prefix;}static fromString(t){let r=E.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=sn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=ripemd160(o).subarray(0,4);if(!Co(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Oe.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return ko(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},ko=(e,t)=>{let r=ripemd160(e);return t+sn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},Co=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},_=(e,t)=>{e.writeVString(t);},Fo=(e,t)=>{e.writeInt16(t);},un=(e,t)=>{e.writeInt64(t);},an=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},Z=(e,t)=>{e.writeUint32(t);},cn=(e,t)=>{e.writeUint64(t);},he=(e,t)=>{e.writeByte(t?1:0);},pn=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},I=(e,t)=>{let r=bt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},xe=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},ge=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(X.from(t).key);},ln=(e=null)=>(t,r)=>{r=vt.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},dn=ln(),er=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},L=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},Re=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},z=le([["weight_threshold",Z],["account_auths",er(_,pe)],["key_auths",er(ge,pe)]]),qo=le([["account",_],["weight",pe]]),tr=le([["base",I],["quote",I]]),Io=le([["account_creation_fee",I],["maximum_block_size",Z],["hbd_interest_rate",pe]]),F=(e,t)=>{let r=le(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},C={};C.account_create=F(R.account_create,[["fee",I],["creator",_],["new_account_name",_],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",_]]);C.account_create_with_delegation=F(R.account_create_with_delegation,[["fee",I],["delegation",I],["creator",_],["new_account_name",_],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",_],["extensions",L(se)]]);C.account_update=F(R.account_update,[["account",_],["owner",Re(z)],["active",Re(z)],["posting",Re(z)],["memo_key",ge],["json_metadata",_]]);C.account_witness_proxy=F(R.account_witness_proxy,[["account",_],["proxy",_]]);C.account_witness_vote=F(R.account_witness_vote,[["account",_],["witness",_],["approve",he]]);C.cancel_transfer_from_savings=F(R.cancel_transfer_from_savings,[["from",_],["request_id",Z]]);C.change_recovery_account=F(R.change_recovery_account,[["account_to_recover",_],["new_recovery_account",_],["extensions",L(se)]]);C.claim_account=F(R.claim_account,[["creator",_],["fee",I],["extensions",L(se)]]);C.claim_reward_balance=F(R.claim_reward_balance,[["account",_],["reward_hive",I],["reward_hbd",I],["reward_vests",I]]);C.comment=F(R.comment,[["parent_author",_],["parent_permlink",_],["author",_],["permlink",_],["title",_],["body",_],["json_metadata",_]]);C.comment_options=F(R.comment_options,[["author",_],["permlink",_],["max_accepted_payout",I],["percent_hbd",pe],["allow_votes",he],["allow_curation_rewards",he],["extensions",L(pn([le([["beneficiaries",L(qo)]])]))]]);C.convert=F(R.convert,[["owner",_],["requestid",Z],["amount",I]]);C.create_claimed_account=F(R.create_claimed_account,[["creator",_],["new_account_name",_],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",_],["extensions",L(se)]]);C.custom=F(R.custom,[["required_auths",L(_)],["id",pe],["data",dn]]);C.custom_json=F(R.custom_json,[["required_auths",L(_)],["required_posting_auths",L(_)],["id",_],["json",_]]);C.decline_voting_rights=F(R.decline_voting_rights,[["account",_],["decline",he]]);C.delegate_vesting_shares=F(R.delegate_vesting_shares,[["delegator",_],["delegatee",_],["vesting_shares",I]]);C.delete_comment=F(R.delete_comment,[["author",_],["permlink",_]]);C.escrow_approve=F(R.escrow_approve,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Z],["approve",he]]);C.escrow_dispute=F(R.escrow_dispute,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Z]]);C.escrow_release=F(R.escrow_release,[["from",_],["to",_],["agent",_],["who",_],["receiver",_],["escrow_id",Z],["hbd_amount",I],["hive_amount",I]]);C.escrow_transfer=F(R.escrow_transfer,[["from",_],["to",_],["hbd_amount",I],["hive_amount",I],["escrow_id",Z],["agent",_],["fee",I],["json_meta",_],["ratification_deadline",xe],["escrow_expiration",xe]]);C.feed_publish=F(R.feed_publish,[["publisher",_],["exchange_rate",tr]]);C.limit_order_cancel=F(R.limit_order_cancel,[["owner",_],["orderid",Z]]);C.limit_order_create=F(R.limit_order_create,[["owner",_],["orderid",Z],["amount_to_sell",I],["min_to_receive",I],["fill_or_kill",he],["expiration",xe]]);C.limit_order_create2=F(R.limit_order_create2,[["owner",_],["orderid",Z],["amount_to_sell",I],["exchange_rate",tr],["fill_or_kill",he],["expiration",xe]]);C.recover_account=F(R.recover_account,[["account_to_recover",_],["new_owner_authority",z],["recent_owner_authority",z],["extensions",L(se)]]);C.request_account_recovery=F(R.request_account_recovery,[["recovery_account",_],["account_to_recover",_],["new_owner_authority",z],["extensions",L(se)]]);C.reset_account=F(R.reset_account,[["reset_account",_],["account_to_reset",_],["new_owner_authority",z]]);C.set_reset_account=F(R.set_reset_account,[["account",_],["current_reset_account",_],["reset_account",_]]);C.set_withdraw_vesting_route=F(R.set_withdraw_vesting_route,[["from_account",_],["to_account",_],["percent",pe],["auto_vest",he]]);C.transfer=F(R.transfer,[["from",_],["to",_],["amount",I],["memo",_]]);C.transfer_from_savings=F(R.transfer_from_savings,[["from",_],["request_id",Z],["to",_],["amount",I],["memo",_]]);C.transfer_to_savings=F(R.transfer_to_savings,[["from",_],["to",_],["amount",I],["memo",_]]);C.transfer_to_vesting=F(R.transfer_to_vesting,[["from",_],["to",_],["amount",I]]);C.vote=F(R.vote,[["voter",_],["author",_],["permlink",_],["weight",Fo]]);C.withdraw_vesting=F(R.withdraw_vesting,[["account",_],["vesting_shares",I]]);C.witness_update=F(R.witness_update,[["owner",_],["url",_],["block_signing_key",ge],["props",Io],["fee",I]]);C.witness_set_properties=F(R.witness_set_properties,[["owner",_],["props",er(_,dn)],["extensions",L(se)]]);C.account_update2=F(R.account_update2,[["account",_],["owner",Re(z)],["active",Re(z)],["posting",Re(z)],["memo_key",Re(ge)],["json_metadata",_],["posting_json_metadata",_],["extensions",L(se)]]);C.create_proposal=F(R.create_proposal,[["creator",_],["receiver",_],["start_date",xe],["end_date",xe],["daily_pay",I],["subject",_],["permlink",_],["extensions",L(se)]]);C.update_proposal_votes=F(R.update_proposal_votes,[["voter",_],["proposal_ids",L(un)],["approve",he],["extensions",L(se)]]);C.remove_proposal=F(R.remove_proposal,[["proposal_owner",_],["proposal_ids",L(un)],["extensions",L(se)]]);var Do=le([["end_date",xe]]);C.update_proposal=F(R.update_proposal,[["proposal_id",cn],["creator",_],["daily_pay",I],["subject",_],["permlink",_],["extensions",L(pn([se,Do]))]]);C.collateralized_convert=F(R.collateralized_convert,[["owner",_],["requestid",Z],["amount",I]]);C.recurrent_transfer=F(R.recurrent_transfer,[["from",_],["to",_],["amount",I],["memo",_],["recurrence",pe],["executions",pe],["extensions",L(le([["type",an],["value",le([["pair_id",an]])]]))]]);var Ko=(e,t)=>{let r=C[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},Bo=le([["ref_block_num",pe],["ref_block_prefix",Z],["expiration",xe],["operations",L(Ko)],["extensions",L(_)]]),Mo=le([["from",ge],["to",ge],["nonce",cn],["check",Z],["encrypted",ln()]]),de={Asset:I,Memo:Mo,Price:tr,PublicKey:ge,String:_,Transaction:Bo,UInt16:pe,UInt32:Z};var et=e=>new Promise(t=>setTimeout(t,e));var No=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function yn(){return No?{"User-Agent":E.userAgent}:{}}var ee=class extends Error{constructor(r){super(r.message);A(this,"name","RPCError");A(this,"data");A(this,"code");A(this,"stack");this.code=r.code,"data"in r&&(this.data=r.data);}},Fe=class extends Error{constructor(r,n,i={}){super(n);A(this,"node");A(this,"rateLimitMs");A(this,"isRateLimit");this.node=r,this.rateLimitMs=i.rateLimitMs??0,this.isRateLimit=i.isRateLimit??false;}};function hn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Qo=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Ho=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Uo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function Vo(e){if(!e)return false;if(e instanceof Fe)return true;if(e instanceof ee)return false;let t=Uo(e);return !!(Qo.some(r=>t.includes(r))||Ho.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function rr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function wn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var jo=1e4,Lo=6e4,$o=12e4,fn=2,mn=6e4,gn=12e4,Wo=30,tt=.3,nr=3,rt=5*6e4,_n=6e4,bn=1e3,vn=2e3,Pt=class{constructor(){A(this,"health",new Map);}getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=nr&&i-o.updatedAt<=rt?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>rt&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:tt*r+(1-tt)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>rt?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=tt*r+(1-tt)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=fn&&(o.cooldownUntil=i+mn),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,fn),o.lastFailureTime=i,o.cooldownUntil=i+mn,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>$o&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(jo*2**n.rateLimitStreak,Lo);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=gn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=gn&&o-n.headBlock>Wo)}getOrderedNodes(t,r){let n=[],i=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):i.push(c);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,o)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=nr&&r-t.latencyUpdatedAt<=rt}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:bn}pickReprobeCandidate(t,r){let n=r-_n,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),c=Math.max(a.latencyUpdatedAt,a.lastProbeAt);c<=n&&c=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(E.resilience.hedgeBucketCapacity,this.tokens+E.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>E.resilience.hedgeBucketCapacity&&(this.tokens=E.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=E.resilience.hedgeBucketCapacity){this.tokens=t;}},or=new ir;function Ot(e,t,r,n,i){let o=E.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function sr(e,t,r,n){r instanceof Fe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof ee?e.recordFailure(t,n):e.recordFailure(t);}function An(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function Go(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function Pn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Go()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function ar(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var nt=async(e,t,r,n=E.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=Pn(n),{signal:l,cleanup:f}=ar(c,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...yn()},signal:l});if(y.status===429)throw new Fe(e,"HTTP 429 Rate Limited",{rateLimitMs:hn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new Fe(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let S=h.error;throw "message"in S&&"code"in S?new ee(S):h.error}throw h}catch(y){if(y instanceof ee||y instanceof Fe||o?.aborted)throw y;if(i)return nt(e,t,r,n,false,o);throw y}finally{m();}};function At(){return et(50+Math.random()*50)}function zo(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,S=0,x=false,P=false,O,W,V=0,M=[],H=Y=>{if(!h){h=true,W!==void 0&&(clearTimeout(W),W=void 0);for(let q of M)q.signal.aborted||q.abort();Y();}},G=(Y,q)=>{S++;let me=new AbortController;M.push(me);let Ze=ar(me.signal,p),xo=Ot($,Y,t,s,a),Wt=Date.now();q||(V=Wt),nt(Y,t,r,xo,false,Ze.signal).then(oe=>{if(Ze.cleanup(),S--,q||(P=true),!h){if(f&&!f(oe)){if($.recordDefectiveResponse(Y,n),O=new Error(`[hive-tx] response validation failed for ${t} from ${Y}`),!q&&!x){H(()=>y(O));return}S===0&&H(()=>y(O));return}$.recordSuccess(Y,n,Date.now()-Wt,t),An($,Y,t,oe),q?P||$.recordCensoredLatency(i,Date.now()-V,t):x||or.refill(),H(()=>m(oe));}}).catch(oe=>{if(Ze.cleanup(),S--,q||(P=true),!h){if(p?.aborted){H(()=>y(oe));return}if(oe instanceof ee&&!rr(oe.code,oe.message)){H(()=>y(oe));return}if(sr($,Y,oe,n),$.recordSlowFailure(Y,Date.now()-Wt,t),O=oe,!q&&!x){H(()=>y(oe));return}S===0&&H(()=>y(O));}});};G(i,false);let Te=$.getUsableLatencyMs(i,t)??0,Xe=Ot($,i,t,s,a),$t=Math.min(Math.max(E.resilience.hedgeDelayFloorMs,E.resilience.hedgeDelayFactor*Te),.8*Xe);W=setTimeout(()=>{if(W=void 0,h||p?.aborted||Date.now()>=c)return;let Y=o.filter(me=>$.isNodeHealthy(me,n));if(Y.length===0)return;let q=Y[Math.floor(Math.random()*Y.length)];or.trySpend()&&(x=true,l(q),G(q,true));},$t);})}var g=async(e,t=[],r,n=E.retry,i,o)=>{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??E.timeout,c=wn(e),p=Date.now()+E.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=$.getOrderedNodes(E.nodes,c),h=y.find(P=>!l.has(P));h||(l.clear(),h=y[0]),l.add(h);let S=[];if(E.resilience.hedge&&$.getUsableLatencyMs(h,e)!==void 0&&(S=y.filter(P=>!l.has(P)&&$.isNodeHealthy(P,c)).slice(0,3)),S.length>0)try{return await zo({method:e,params:t,api:c,primary:h,hedgePool:S,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:P=>l.add(P),validate:o})}catch(P){if(P instanceof ee&&!rr(P.code,P.message)||i?.aborted)throw P;f=P,m{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let i=wn(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await nt(p,e,t,r,!1,n);return $.recordSuccess(p,i),l}catch(l){if(l instanceof ee||n?.aborted||(sr($,p,l,i),s=l,!Vo(l)))throw l}}throw s},Jo={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function re(e,t,r,n,i=E.retry,o){if(!Array.isArray(E.restNodes))throw new Error("config.restNodes is not an array");if(E.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??E.timeout,c=Date.now()+E.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=E.restNodesByApi?.[e]?.length?E.restNodesByApi[e]:E.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=c);h++){let S=Ee.getOrderedNodes(l,e),x=S.find(q=>!f.has(q));x||(f.clear(),x=S[0]),f.add(x);let P=x+Jo[e],O=t,W=r||{},V=new Set;Object.entries(W).forEach(([q,me])=>{O.includes(`{${q}}`)&&(O=O.replace(`{${q}}`,encodeURIComponent(String(me))),V.add(q));});let M=new URL(P+O);if(Object.entries(W).forEach(([q,me])=>{V.has(q)||(Array.isArray(me)?me.forEach(Ze=>M.searchParams.append(q,String(Ze))):M.searchParams.set(q,String(me)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:H,cleanup:G}=Pn(Ot(Ee,x,p,a,s)),{signal:Te,cleanup:Xe}=ar(H,o),$t=()=>{G(),Xe();},Y=Date.now();try{let q=await fetch(M.toString(),{signal:Te,headers:yn()});if(q.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(q.status===429)throw Ee.recordRateLimit(x,hn(q.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${x}`);if(q.status===503)throw Ee.recordFailure(x,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${x}`);if(!q.ok)throw Ee.recordFailure(x,e),y=!0,new Error(`HTTP ${q.status} from ${x}`);return Ee.recordSuccess(x,e,Date.now()-Y,p),q.json()}catch(q){if(q?.message?.includes("HTTP 404")||o?.aborted)throw q;y||Ee.recordFailure(x,e),Ee.recordSlowFailure(x,Date.now()-Y,p),m=q,h{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an Array");if(r>E.nodes.length)throw new Error("quorum > config.nodes.length");let o=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(E.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let c=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Yo(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Yo(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var Zo=hexToBytes(E.chain_id),qe=class e{constructor(t){A(this,"transaction");A(this,"expiration",6e4);A(this,"txId");A(this,"createTransaction",async t=>{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};});t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Ue("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof ee&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await et(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return Oe.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new X(secp256k1.getPublicKey(this.key),t)}toString(){return rs(new Uint8Array([...Cn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},Tn=e=>sha256(sha256(e)),rs=e=>{let t=Tn(e);return sn.encode(new Uint8Array([...e,...t.slice(0,4)]))},ns=e=>{let t=sn.decode(e);if(!Sn(t.slice(0,1),Cn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=Tn(n).slice(0,4);if(!Sn(r,i))throw new Error("Private key checksum mismatch");return n},Sn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nIn(e,t,n,r),qn=(e,t,r,n,i)=>In(e,t,r,n,i).message,In=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let c=sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),f=sha256(c).subarray(0,4),m=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=as(n,l,p);}else n=us(n,l,p);return {nonce:o,message:n,checksum:y}},as=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},us=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},cr=null,cs=()=>{if(cr===null){let r=secp256k1.utils.randomSecretKey();cr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++cr%65536;return e=e<{let t=gs(e,33);return new X(t)},ls=e=>e.readUint64(),ds=e=>e.readUint32(),fs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},ms=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function gs(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var ys=ms([["from",Dn],["to",Dn],["nonce",ls],["check",ds],["encrypted",fs]]),Kn={Memo:ys};var Mn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Qn(),e=Hn(e),t=hs(t);let i=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Fn(e,t,o,n),p=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);de.Memo(p,{check:c,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+sn.encode(l)},Nn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Qn(),e=Hn(e);let r=Kn.Memo(sn.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new X(n.key).toString()?new X(i.key):new X(n.key);r=qn(e,p,o,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Et,Qn=()=>{if(Et===void 0){let e;Et=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Mn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Nn(t,n);}finally{Et=e==="#memo\u7231";}}if(Et===false)throw new Error("This environment does not support encryption.")},Hn=e=>typeof e=="string"?U.fromString(e):e,hs=e=>typeof e=="string"?X.fromString(e):e,Un={decode:Nn,encode:Mn};var ie={};yt(ie,{buildWitnessSetProperties:()=>Ps,makeBitMaskFilter:()=>vs,operations:()=>bs,validateUsername:()=>_s});var _s=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(As,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),As=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=de.UInt32;break;case "hbd_interest_rate":i=de.UInt16;break;case "url":i=de.String;break;case "hbd_exchange_rate":i=de.Price;break;case "account_creation_fee":i=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,Os(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},Os=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function _m(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function Vn(e){try{return U.fromString(e),!0}catch{return false}}async function te(e,t){let r=new qe;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Ue("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function jn(e,t){let r=new qe;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var Es=432e3;function Ln(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/Es,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function Ss(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function pr(e){let t=Ss(e)*1e6;return Ln(t,e.voting_manabar)}function St(e){return Ln(Number(e.max_rc),e.rc_manabar)}var $n=(c=>(c.COMMON="common",c.INFO="info",c.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",c.MISSING_AUTHORITY="missing_authority",c.TOKEN_EXPIRED="token_expired",c.NETWORK="network",c.TIMEOUT="timeout",c.VALIDATION="validation",c))($n||{});function Ve(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function ks(e){let t=Ve(e);return [t.message,t.type]}function we(e){let{type:t}=Ve(e);return t==="missing_authority"||t==="token_expired"}function Cs(e){let{type:t}=Ve(e);return t==="insufficient_resource_credits"}function Ts(e){let{type:t}=Ve(e);return t==="info"}function Rs(e){let{type:t}=Ve(e);return t==="network"||t==="timeout"}async function _e(e,t,r,n,i="posting",o,s,a="async"){let c=n?.adapter;switch(e){case "key":{if(!c)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(c.getOwnerKey)p=await c.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":c.getActiveKey&&(p=await c.getActiveKey(t));break;case "memo":if(c.getMemoKey)p=await c.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await c.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=U.fromString(p);return a==="async"?await jn(r,l):await te(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new Wn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&we(l))return await c.broadcastWithHiveSigner(t,r,i);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!c?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await c.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function qs(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await _e(l,e,t,r,n,void 0,void 0,i)}catch(m){if(we(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(we(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await _e(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let S;switch(n){case "owner":o.getOwnerKey&&(S=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(S=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(S=await o.getMemoKey(e));break;default:S=await o.getPostingKey(e);break}S?y=S:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let S=await o.getAccessToken(e);S&&(h=S);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await _e(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!we(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async c=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(c);try{if(i?.enableFallback!==!1&&i?.adapter)return await qs(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=U.fromString(l);return await te(p,m)}let f=i?.accessToken;if(f)return (await new Wn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof ee?new Error(l.message):l}}})}async function Gn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let c=U.fromString(o);return te([["custom_json",i]],c)}let s=n?.accessToken;if(s)return (await new Wn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,c,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,c,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Dm=4e3;function k(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function be(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var Ie=(()=>{try{return !1}catch{return false}})(),Ks=()=>{try{return ""}catch{return}},ve=1e4,zn=120*1e3,kt,Bs;function Ms(){return kt?kt():Bs??(Bs=new QueryClient)}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return E.nodes},heliusApiKey:Ks(),get queryClient(){return Ms()},set queryClient(e){kt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},N;(P=>{function e(O){d.queryClient=O;}P.setQueryClient=e;function t(O){kt=O;}P.setQueryClientResolver=t;function r(O){d.privateApiHost=O;}P.setPrivateApiHost=r;function n(O){d.clientId=O;}P.setClientId=n;function i(O){if(typeof O!="string"||O.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=O;}P.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}P.getValidatedBaseUrl=o;function s(O){d.pollsApiHost=O;}P.setPollsApiHost=s;function a(O){d.imageHost=O;}P.setImageHost=a;function c(O){zt(O);}P.setHiveNodes=c;function p(O){Jt(O);}P.setRestNodes=p;function l(O){Yt(O);}P.setRestNodesByApi=l;function f(O){Xt(O);}P.setUserAgent=f;function m(O){Zt(O);}P.setResilience=m;function y(O){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(O))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(O))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(O))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(O)||/\.\+\.\+/.test(O))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let W=/\.?\{(\d+),(\d+)\}/g,V;for(;(V=W.exec(O))!==null;){let[,M,H]=V;if(parseInt(H,10)-parseInt(M,10)>1e3)return {safe:false,reason:`excessive range: {${M},${H}}`}}return {safe:true}}function h(O){let W=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],V=5;for(let M of W){let H=Date.now();try{O.test(M);let G=Date.now()-H;if(G>V)return {safe:!1,reason:`runtime test exceeded ${V}ms (took ${G}ms on input length ${M.length})`}}catch(G){return {safe:false,reason:`runtime test threw error: ${G}`}}}return {safe:true}}function S(O,W=200){try{if(!O)return Ie&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(O.length>W)return Ie&&console.warn(`[SDK] DMCA pattern rejected: length ${O.length} exceeds max ${W} - pattern: ${O.substring(0,50)}...`),null;let V=y(O);if(!V.safe)return Ie&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${V.reason}) - pattern: ${O.substring(0,50)}...`),null;let M;try{M=new RegExp(O);}catch(G){return Ie&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${O.substring(0,50)}...`,G),null}let H=h(M);return H.safe?M:(Ie&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${H.reason}) - pattern: ${O.substring(0,50)}...`),null)}catch(V){return Ie&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${O.substring(0,50)}...`,V),null}}function x(O={}){let W=G=>Array.isArray(G)?G.filter(Te=>typeof Te=="string"):[],V=O||{},M={accounts:W(V.accounts),tags:W(V.tags),patterns:W(V.posts)};d.dmcaAccounts=M.accounts,d.dmcaTags=M.tags,d.dmcaPatterns=M.patterns,d.dmcaTagRegexes=M.tags.map(G=>S(G)).filter(G=>G!==null),d.dmcaPatternRegexes=[];let H=M.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Ie&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${M.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${M.tags.length} compiled (${H} rejected)`),console.log(` - Post patterns: ${M.patterns.length} (using exact string matching)`),H>0&&console.warn(`[SDK] ${H} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}P.setDmcaLists=x;})(N||(N={}));function Wm(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,Jn;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(Jn||(Jn={}));function zm(e){return btoa(JSON.stringify(e))}function Jm(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Yn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Yn||{}),Ct=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Ct||{});function T(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Yn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Ct[e.nai]}}var lr;function w(){if(!lr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");lr=globalThis.fetch.bind(globalThis);}return lr}function Xn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Us(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function ae(e,t){return Us(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function je(e,t){return e/1e6*t}function Zn(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var ei=60*1e3;function Ae(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:ei,staleTime:ei,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=T(t.total_vesting_shares).amount,a=T(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=T(r.current_median_history.base).amount,l=T(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=T(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",S=Number(i.content_constant??0),x=String(o.current_hardfork_version??"0.0.0"),P=Number(o.last_hardfork??0),O=t.hbd_print_rate,W=t.hbd_interest_rate,V=t.head_block_number,M=a,H=s,G=T(t.virtual_supply).amount,Te=t.vesting_reward_percent||0,Xe=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:S,currentHardforkVersion:x,lastHardfork:P,hbdPrintRate:O,hbdInterestRate:W,headBlock:V,totalVestingFund:M,totalVestingShares:H,virtualSupply:G,vestingRewardPercent:Te,accountCreationFee:Xe,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function dg(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function De(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var u={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>De("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>De("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>De("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>De("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>De("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>De("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>De("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function hg(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await w()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function vg(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function xg(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function zs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Cg(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??zs()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw c.status=i.status,c.data=a,c}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Ys(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function qg(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Ys()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Zs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Bg(e,t){return useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??Zs()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await w()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),c={};try{c=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:c})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function dr(e){return !e.posting_json_metadata&&!e.json_metadata}function ta(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function Q(e){return queryOptions({queryKey:u.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(dr(i)&&ta(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!dr(l[0])));if(p[0]&&!dr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=Ke(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:c,profile:o}},enabled:!!e,staleTime:6e4})}var ra=new Set(["__proto__","constructor","prototype"]);function Tt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ti(e,t){let r={...e};for(let n of Object.keys(t)){if(ra.has(n))continue;let i=t[n],o=r[n];Tt(i)&&Tt(o)?r[n]=ti(o,i):r[n]=i;}return r}function na(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function Ke(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function ri(e){return Ke(e?.posting_json_metadata)}function ni(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ke(e.posting_json_metadata)).length;return Object.keys(Ke(t.posting_json_metadata)).length>r?t:e}function ia(e){if(!e)return {};try{let t=JSON.parse(e);if(Tt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ii({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=ia(e),i=Tt(n.profile)?n.profile:{},o=fr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function fr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=ti(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=na(s.tokens),s.version=2,s}function Rt(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Ke(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function oa(e){return new TextEncoder().encode(e).length}function Le(e){return e?oa(e)<=16:false}function Zg(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Le);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Rt(r??[])}})}function iy(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function cy(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function my(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var oi=1e3,la=20;function _y(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthLe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Ty(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var ga=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Iy(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await w()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,c=typeof a.token=="string"?a.token:void 0;if(!c)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:c,currency:c,address:f,show:y,type:"CHAIN",meta:l},S=[];for(let[x,P]of Object.entries(p))typeof x=="string"&&(ga.has(x)||typeof P!="string"||!P||/^[A-Z0-9]{2,10}$/.test(x)&&S.push({symbol:x,currency:x,address:P,show:y,type:"CHAIN",meta:{address:P,show:y}}));return [h,...S]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function si(e,t){return queryOptions({queryKey:u.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function Vy(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Wy(e,t){return queryOptions({queryKey:u.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Gy(e,t,r=10){return infiniteQueryOptions({queryKey:u.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Xy(e,t){return queryOptions({queryKey:u.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Zy(e,t,r=10){return infiniteQueryOptions({queryKey:u.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function nh(e,t,r){return queryOptions({queryKey:u.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await w()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function ah(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:u.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await w()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function dh(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function wh(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Le(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var K=ie.operations,ai={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.fill_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay]},Sa=Array.from(new Set(Object.values(ai).flat()));function ka(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ca(e){return e.replace(/_operation$/,"")}function Ta(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function Ra(e){if(!Ta(e))return e;let t=T(e),r=Ct[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Fa(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Ra(n);return t}function Eh(e,t=20,r=""){let n=r?ai[r]:Sa;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await re("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ca(m.op.type);return {...Fa(m.op.value),num:ka(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(i),p=a(c),l=i??c.total_pages;if(i===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function Th(){return queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Ih(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=N.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Mh(e){return queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function jh(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Ma=30;function zh(e,t,r){return queryOptions({queryKey:u.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(c=>t==="following"?c.following:c.follower).filter(c=>c.toLowerCase().includes(r.toLowerCase())).slice(0,Ma);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(c=>({name:c.name,full_name:c.metadata.profile?.name||"",reputation:c.reputation,active:c.active}))??[]}})}function ew(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function sw(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Xn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function $e(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await w()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function pw(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function mw(e="feed"){return queryOptions({queryKey:u.posts.promoted(e),queryFn:async()=>{let t=N.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await w()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function _w(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Ow(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function Cw(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function Iw(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function Nw(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function ne(e){return Array.isArray(e)?e.map(t=>ui(t)):ui(e)}function ui(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function ci(e,t,r){try{let n=await xt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function pi(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return queryOptions({queryKey:u.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let c=await ci(e,i,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return ne(p)}let a=n!==void 0?{...s,num:n}:s;return ne(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ue(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function li(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await Ja(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function di(e,t,r){let n=e.map(ot),i=await Promise.all(n.map(o=>li(o,t,void 0,r)));return ne(i)}async function fi(e,t="",r="",n=20,i="",o="",s){let a=await ue("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function mr(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ue("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function ot(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Ja(e="",t="",r="",n,i){let o=await ue("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=ot(o),a=await li(s,r,n,i);return ne(a)}}async function e_(e="",t=""){let r=await ue("get_post_header",{author:e,permlink:t});return r&&ot(r)}async function mi(e,t,r){let n=await ue("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=ot(s);return i}return n}async function gi(e,t=""){return ue("get_community",{name:e,observer:t})}async function t_(e="",t=100,r,n="rank",i=""){return ue("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function yi(e){let t=await ue("normalize_post",{post:e});return t&&ot(t)}async function r_(e){return ue("list_all_subscriptions",{account:e})}async function n_(e){return ue("list_subscribers",{community:e})}async function i_(e,t){return ue("get_relationship_between_accounts",[e,t])}async function Ft(e,t){return ue("get_profiles",{accounts:e,observer:t})}var wi=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(wi||{});function gr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Ya(e,t,r){let n=l=>gr(l.pending_payout_value).amount+gr(l.author_payout_value).amount+gr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function _i(e,t="created",r=true,n){let i=n||d.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return ne(s)},enabled:r&&!!e,select:o=>Ya(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),c=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!c.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function l_(e,t,r,n=true){let i=r||d.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>mi(e,t,i)})}function w_(e,t="posts",r=20,n="",i=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await mr(t,e,o.author??"",o.permlink??"",r,n,s);return ne(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function __(e,t="posts",r="",n="",i=20,o="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await mr(t,e,r,n,i,o,a);return ne(c??[])}})}var bi=new Map;function ru(e){let t=bi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>nu(n,e))}),bi.set(e,t)),t}function nu(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function S_(e,t,r=20,n="",i=true,o={}){return infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:c,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return ne(p)},select:ru(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function k_(e,t="",r="",n=20,i="",o="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let c=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(c="");let p=await fi(e,t,r,n,c,o,a);return ne(p??[])}})}function q_(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function M_(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function U_(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function V_(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function W_(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function G_(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Ai(e){let r=await w()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function X_(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function Z_(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function eb(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ib(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function fu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function ub(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?fu(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:c,tags:p}=s.list[0];return {body:a,title:c,tags:p}},enabled:i})}function db(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function gu(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function yu(e){return {...e,id:e.id??e.post_id}}function ye(e,t){if(!e)return null;let r=e.container??e,n=gu(r,t),i=e.parent?yu(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function hu(e){return Array.isArray(e)?e:[]}async function Pi(e){let t=_i(e,"created",true),r=await d.queryClient.fetchQuery(t),n=hu(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function Oi(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var bu=20;function xi(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??bu}}async function Ei({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let c=N.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=ye(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function bb(e={}){let t=xi(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Ei(t,c,p),getNextPageParam:c=>{if(!(c.lengthEi(t,void 0,c)})}var Au=20;function Pu(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Au}}async function Ou({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=N.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(i)),o&&c.searchParams.set("cursor",o),e.forEach(f=>c.searchParams.append("container",f)),t&&c.searchParams.set("tag",t),r&&c.searchParams.set("author",r),n&&c.searchParams.set("observer",n);let p=await fetch(c.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=ye(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Eb(e={}){let t=Pu(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>Ou(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Pi(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:Oi(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function qb(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await ku(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Tu=40;function Mb(e,t,r=Tu){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>ye(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function Vb(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:u.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>ye(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function Wb(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:c,posts:p})=>({tag:c,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function Xb(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:u.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>ye(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function rv(e){return queryOptions({queryKey:u.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=N.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function av(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>yi(e)})}function Bu(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Si(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function gv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Si(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(pi(m.author,m.permlink));Bu(y)&&l.push(y);}let[f]=a;return {lastDate:f?Si(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function bv(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Ft(e,t)})}function Ev(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await re("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function Rv(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await re("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Dv(){return queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function Kv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Uv(e,t,r){let n=useQueryClient(),{data:i}=useQuery(Q(e));return v(["accounts","update"],e,o=>{let s=ni(n.getQueryData(Q(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ii({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(Q(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=fr({existingProfile:ri(a),profile:s.profile,tokens:s.tokens}),c}),await k(t?.adapter,r,[u.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...Q(e),staleTime:0});}catch{}}})}function Wv(e,t,r,n,i){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=si(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await Gn(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(u.accounts.relations(e,t),o),t&&b().invalidateQueries(Q(t));}})}function yr(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Be(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function Me(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function hr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function wr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Ne(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Lu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Ne(e,o.trim(),r,n))}function $u(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function We(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function Qe(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function ki(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function st(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Qe(e,t,r,n,i),ki(e,i)]}function at(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function ut(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function ct(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function pt(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function lt(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function _r(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function He(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function br(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function vr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function Ar(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function qt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function Wu(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Gu(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return qt(e,t)}function Pr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function Or(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function xr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Er(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function Sr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function zu(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function Ju(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function kr(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Cr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Tr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Rr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Fr(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function qr(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function Yu(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Xu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var Ci=(r=>(r.Buy="buy",r.Sell="sell",r))(Ci||{}),Ti=(r=>(r.EMPTY="",r.SWAP="9",r))(Ti||{});function Dt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function It(e,t=3){return e.toFixed(t)}function Zu(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${It(t,3)} HBD`:`${It(t,3)} HIVE`,p=n==="buy"?`${It(r,3)} HIVE`:`${It(r,3)} HBD`;return Dt(e,c,p,false,s,a)}function Ir(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Dr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function ec(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function tc(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Kr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Br(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Mr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Nr(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let c={...t,account_auths:a};return c.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:c,memo_key:i,json_metadata:o}]}function rc(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function nc(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function ic(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function oc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Qr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Hr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function Ur(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Ge(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function sc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>Ge(e,o.trim(),r,n))}function Vr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function ac(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function uc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function mA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Ar(e,n)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function wA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[qt(e,n)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function AA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function EA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function TA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:n})}function DA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await w()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:c})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(c);o.setQueryData(c,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(S=>({...S,data:S.data.filter(x=>x.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);s?.previousCheck!==void 0&&a.setQueryData(u.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function gc(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Ri(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let c=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=gc(y,n.map((h,S)=>[h[p].createPublic().toString(),S+1])),l};return te([["account_update",{account:e,json_metadata:r.json_metadata,owner:c("owner"),active:c("active"),posting:c("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function LA(e,t){let{data:r}=useQuery(Q(e)),{mutateAsync:n}=Ri(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,i,"owner"),active:U.fromLogin(e,i,"active"),posting:U.fromLogin(e,i,"posting"),memo_key:U.fromLogin(e,i,"memo")}]})},...t})}function YA(e,t,r){let n=useQueryClient(),{data:i}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(i.posting));c.account_auths=c.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:c,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return te([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return t.hsCallbackUrl,Wn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(Q(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function iP(e,t,r,n){let{data:i}=useQuery(Q(e));return useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:c})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await w()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return te([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return r.hsCallbackUrl,Wn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function sP(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function Fi(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function dP(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=Fi(r,o);return te([["account_update",s]],n)},...t})}function yP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Mr(n,i)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function bP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Nr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await k(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function OP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Br(e,n.newAccountName,n.keys):Kr(e,n.newAccountName,n.keys,n.fee)],async()=>{await k(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var jr=300*60*24,Sc=1e4,kc=5e7;function qi(e){let t=T(e.vesting_shares).amount,r=T(e.received_vesting_shares).amount,n=T(e.delegated_vesting_shares).amount,i=T(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Cc(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Tc(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function Rc(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=qi(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Sc/(n*jr)),a=pr(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-kc,0)}function Fc(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Tc(t))return Rc(e,t,n);let i=0;try{if(i=qi(e),!Number.isFinite(i))return 0}catch{return 0}return Cc(i,r,n)}function kP(e){return pr(e).percentage/100}function CP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*jr/1e4}function TP(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/jr;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function RP(e){return St(e).percentage/100}function FP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let c=Fc(e,t,r,n);return Number.isFinite(c)?c/i*o*(s/a):0}var qc={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Ic(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Dc(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function Kc(e){let t=e[0];return t==="custom_json"?Ic(e):t==="create_proposal"||t==="update_proposal"?Dc(e):qc[t]??"posting"}function IP(e){let t="posting";for(let r of e){let n=Kc(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function NP(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=U.fromLogin(e,r,"active"):Vn(r)?n=U.fromString(r):n=U.from(r),te([t],n)}})}function UP(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function $P(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Wn.sendOperation(t,{callback:e},()=>{})})}function JP(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ii(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Di(e,t){return {...e??{},title:t.title,body:t.body}}function i0(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await w()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Di(r,n);i.setQueryData($e(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[o,...a.data]}:a)});}})}function l0(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await w()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ii(s,r,n);i.setQueryData($e(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?o(c):c)}))});}})}function h0(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await w()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData($e(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function J(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function b0(e,t,r,n){let o=await w()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await J(o);return {status:o.status,data:s}}async function v0(e){let r=await w()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await J(r);return {status:r.status,data:n}}async function A0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await w()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await J(s);}async function P0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await w()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return J(s)}async function O0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},c=await w()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function x0(e,t,r){let n={code:e,username:t,token:r},o=await w()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}async function Ki(e,t){let r={code:e};t&&(r.id=t);let i=await w()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Bi(e,t){let r={code:e,url:t},i=await w()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}var Lc="https://i.ecency.com";async function Mi(e,t,r){let n=w(),i=new FormData;i.append("file",e);let o=await n(`${Lc}/hs/${t}`,{method:"POST",body:i,signal:r});return J(o)}async function E0(e,t,r,n){let i=w(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return J(s)}async function Ni(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Qi(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await w()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return J(a)}async function Hi(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},c=await w()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function Ui(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Vi(e,t,r,n,i,o,s,a){let c={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(c.options=o);let l=await w()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return J(l)}async function ji(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Li(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function S0(e,t,r){let n={code:e,author:t,permlink:r},o=await w()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}async function k0(e,t,r){let n={username:e,email:t,friend:r},o=await w()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}function q0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return Qi(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(u.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function M0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Hi(t,i,o,s,a,c)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function j0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return Ui(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let c=o.getQueryData(s);c&&o.setQueryData(s,c.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);n?.(i);}})}function z0(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Vi(t,i,o,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function eO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return ji(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function oO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return Li(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)}),o.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function pO(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Bi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function gO(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Ni(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],c=>c?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},c=>c&&{...c,pages:c.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function _O(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Mi(r,n,i),onSuccess:e,onError:t})}function Bt(e,t){return `/@${e}/${t}`}function tp(e,t,r){return (r??b()).getQueryData(u.posts.entry(Bt(e,t)))}function rp(e,t){(t??b()).setQueryData(u.posts.entry(Bt(e.author,e.permlink)),e);}function Kt(e,t,r,n){let i=n??b(),o=Bt(e,t),s=i.getQueryData(u.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(u.posts.entry(o),a),s}var Se;(a=>{function e(c,p,l,f,m){Kt(c,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(c,p,l,f){Kt(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){Kt(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){Kt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function i(c,p){c.forEach(l=>rp(l,p));}a.updateEntries=i;function o(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Bt(c,p))});}a.invalidateEntry=o;function s(c,p,l){return tp(c,p,l)}a.getEntry=s;})(Se||(Se={}));function np(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function ip(e,t,r){let n=Se.getEntry(t.author,t.permlink,r);if(!n?.active_votes||np(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);Se.updateVotes(t.author,t.permlink,i,o,r);}function EO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[yr(e,n,i,o)],async(n,i)=>{ip(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function RO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[wr(e,n,i,o??false)],async(n,i)=>{let o=Se.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));Se.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function DO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(Be(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Me(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let c=[u.accounts.full(e),u.resourceCredits.account(e)];if(!o){c.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;c.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(c);}},t,"posting",{broadcastMode:r})}function MO(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function $i(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[c,p]of a)p&&(s.set(c,p),o.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Wi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function NO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(u.posts.entry(o));return s&&i.setQueryData(u.posts.entry(o),{...s,...r}),s}function QO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(u.posts.entry(o),r);}function LO(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[hr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:$i(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Wi(s);}})}function zO(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(Be(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;i.push(Me(n.author,n.permlink,o,s,a,c,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function ZO(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(Be(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Me(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[u.resourceCredits.account(e)];s.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,c=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===c}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function nx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[Ur(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var op=[3e3,3e3,3e3],sp=e=>new Promise(t=>setTimeout(t,e));async function ap(e,t){return g("condenser_api.get_content",[e,t])}async function up(e,t,r=0,n){let i=n?.delays??op,o;try{o=await ap(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await sp(s),up(e,t,r+1,n)}var ze={};yt(ze,{useRecordActivity:()=>Lr});function pp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Lr(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=w(),i=pp(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function fx(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function wx(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function Ax(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Mt="threespeakfund",kx=1100;function mp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function Cx(e,t){if(!mp(t))return e;let r=e.find(n=>n.account===Mt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Mt?{...n,weight:1100}:n):[...e,{account:Mt,weight:1100}]}function Tx(e){return e===Mt}var Gr={};yt(Gr,{getAccountTokenQueryOptions:()=>Wr,getAccountVideosQueryOptions:()=>bp});var $r={};yt($r,{getDecodeMemoQueryOptions:()=>hp});function hp(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Wn.Client({accessToken:r}).decode(t)}})}var Gi={queries:$r};function Wr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await w()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=Gi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function bp(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Wr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await w()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var Wx={queries:Gr};function Zx(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await w()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function nE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await w()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function aE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function lE(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}var zi={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function mE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return zi;let{current_mana:i,max_mana:o}=St(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...zi,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,c=s*a,p=i{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function PE(e,t,r,n){let{mutateAsync:i}=Lr(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function SE(e){let t=e?.replace("@","");return queryOptions({queryKey:u.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await w()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var kp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function CE(e,t){return kp.find(r=>r.tier===e&&r.id===t)}var Cp=25;function Tp(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function TE(e){return Tp(e)>Cp}var RE=300,FE=2;function qp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function Ip(e){let r=await w()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:qp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function KE(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return Ip(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function QE(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[kr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function jE(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Cr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function GE(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[qr(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function XE(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[Tr(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===o.account);return p>=0?c[p]=[c[p][0],o.role,c[p][2]??""]:c.push([o.account,o.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function rS(e,t,r,n){return v(["communities","update",e],t,i=>[Rr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function sS(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Vr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(i.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function pS(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Fr(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${i.account}/${i.permlink}`),[...u.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function gS(e,t,r=100,n=void 0,i=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function bS(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function xS(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>gi(e??"",t)})}var Ji=100;async function Yi(e,t){return await g("bridge.list_subscribers",{community:e,limit:Ji,...t?{last:t}:{}})??[]}function RS(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>Yi(e,null),staleTime:6e4})}function FS(e){return infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Yi(e,t),getNextPageParam:t=>t?.length>=Ji?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function MS(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function US(){return queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var Up=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Up||{}),jS={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function $S(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function WS({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function YS(e,t){return queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function tk(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Lp=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(Lp||{});var $p=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))($p||{}),Xi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Wp=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Wp||{});function uk(e,t,r){return queryOptions({queryKey:u.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Xi]})})}function dk(){return queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function yk(e){return queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function Xp(e,t){return {...e,read:!t||t===e.id?1:e.read}}function Zi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function Pk(e,t,r,n){let i=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!(!e||!t))return Ki(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return Zi(f)}});a.forEach(([l,f])=>{if(f&&Zi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>Xp(h,o)))};i.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=i.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(c,p-1):i.setQueryData(c,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{i.setQueryData(c,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:u.notifications._prefix});}})}function Sk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Pr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function Rk(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function Hk(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Rt(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function Lk(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function zk(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[Sr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function Zk(e,t,r){return v(["proposals","create"],e,n=>[Er(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function nC(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthre("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function lC(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function gC(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function _C(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function PC(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function SC(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function RC(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function KC(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function QC(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await w()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function jC(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function GC(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function fe(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ce(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function yl(e){if(!e||typeof e!="object")return;let t=e;return {name:fe(t.name)??"",symbol:fe(t.symbol)??"",layer:fe(t.layer)??"hive",balance:ce(t.balance)??0,fiatRate:ce(t.fiatRate)??0,currency:fe(t.currency)??"usd",precision:ce(t.precision)??3,address:fe(t.address),error:fe(t.error),pendingRewards:ce(t.pendingRewards),pendingRewardsFiat:ce(t.pendingRewardsFiat),liquid:ce(t.liquid),liquidFiat:ce(t.liquidFiat),savings:ce(t.savings),savingsFiat:ce(t.savingsFiat),staked:ce(t.staked),stakedFiat:ce(t.stakedFiat),iconUrl:fe(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ce(t.apr)}}function hl(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function wl(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function eo(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${N.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=hl(o).map(a=>yl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:wl(o)??e,currency:fe(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Nt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Ae()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Ae().queryKey),r=b().getQueryData(Q(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=T(r.balance).amount,s=T(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function to(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Ae()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Q(e).queryKey),r=b().getQueryData(Ae().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:T(t.hbd_balance).amount+T(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:T(t.hbd_balance).amount},{name:"savings",balance:T(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Al(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*c*p/f).toFixed(3)}function ro(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Ae()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Ae().queryKey),r=b().getQueryData(Q(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=T(r.vesting_shares).amount,a=T(r.delegated_vesting_shares).amount,c=T(r.received_vesting_shares).amount,p=T(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=Zn(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+je(s,t.hivePerMVests).toFixed(3),y=+je(a,t.hivePerMVests).toFixed(3),h=+je(c,t.hivePerMVests).toFixed(3),S=+je(l,t.hivePerMVests).toFixed(3),x=+je(f,t.hivePerMVests).toFixed(3),P=Math.max(m-S,0),O=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+P.toFixed(3),apr:Al(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+O.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...S>0?[{name:"pending_power_down",balance:+S.toFixed(3)}]:[],...x>0&&x!==S?[{name:"next_power_down",balance:+x.toFixed(3)}]:[]]}}})}var B=ie.operations,zr={transfers:[B.transfer,B.transfer_to_savings,B.transfer_from_savings,B.cancel_transfer_from_savings,B.recurrent_transfer,B.fill_recurrent_transfer,B.escrow_transfer,B.fill_recurrent_transfer],"market-orders":[B.fill_convert_request,B.fill_order,B.fill_collateralized_convert_request,B.limit_order_create2,B.limit_order_create,B.limit_order_cancel],interests:[B.interest],"stake-operations":[B.return_vesting_delegation,B.withdraw_vesting,B.transfer_to_vesting,B.set_withdraw_vesting_route,B.update_proposal_votes,B.fill_vesting_withdraw,B.account_witness_proxy,B.delegate_vesting_shares],rewards:[B.author_reward,B.curation_reward,B.producer_reward,B.claim_reward_balance,B.comment_benefactor_reward,B.liquidity_reward,B.proposal_pay],"":[]};var _T=Object.keys(ie.operations);var no=ie.operations,AT=no,PT=Object.entries(no).reduce((e,[t,r])=>(e[r]=t,e),{});var io=ie.operations;function Ol(e){return Object.prototype.hasOwnProperty.call(io,e)}function dt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in zr){zr[a].forEach(c=>o.add(c));return}Ol(a)&&o.add(io[a]);});let s=Sl(Array.from(o));return {filterKey:i,filterArgs:s}}function Jr(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function xl(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function El(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Sl(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,El(Number(s),t),...n])).map(c=>({num:c[0],type:c[1].op[0],timestamp:c[1].timestamp,trx_id:c[1].trx_id,...c[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return T(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return T(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return T(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=T(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return T(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function IT(e,t=20,r=[]){let{filterKey:n}=dt(r),i=Jr(r);return infiniteQueryOptions({...Qt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return T(c.hbd_payout).amount>0;case "claim_reward_balance":return T(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return T(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return T(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=T(c.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(c.type)}}))})})}function NT(e,t=20,r=[]){let{filterKey:n}=dt(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return infiniteQueryOptions({...Qt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return T(p.vesting_payout).amount>0;case "claim_reward_balance":return T(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(T(p.amount).symbol);case "fill_recurrent_transfer":let m=T(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function oo(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Yr(e,t){return new Date(e.getTime()-t*1e3)}function VT(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,oo(t),oo(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[Yr(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[Yr(n,Math.max(100*e,28800)),Yr(n,e)]})}function WT(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function YT(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function rR(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>T(n.vesting_shares).amount-T(r.vesting_shares).amount)})}function sR(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function pR(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function mR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function wR(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function AR(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=w(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function so(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function ER(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[so(i),so(n),e])})}function TR(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function IR(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function MR(e,t,r){return v(["market","limit-order-create"],e,n=>[Dt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function UR(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Ir(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function ft(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function LR(e,t,r,n){let i=w(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return ft(s)}async function ao(e){if(e==="hbd")return 1;let t=w(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await ft(n)).hive_dollar[e]}async function $R(e,t){let n=await w()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return ft(n)}async function WR(){let t=await w()(d.privateApiHost+"/private-api/market-data/latest");return ft(t)}async function GR(){let t=await w()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return ft(t)}var Ul={"Content-type":"application/json"};async function Vl(e){let t=w(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Ul});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function ke(e,t){try{return await Vl(e)}catch{return t}}async function YR(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([ke({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),ke({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((c,p)=>{let l=Number(c.price??0);return Number(p.price??0)-l}),s=a=>a.sort((c,p)=>{let l=Number(c.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function XR(e,t=50){return ke({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function ZR(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([ke({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),ke({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),c=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...c].sort((p,l)=>l.timestamp-p.timestamp)}async function jl(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return ke({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Je(e,t){return jl(t,e)}async function Ht(e){return ke({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Ut(e){return ke({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function uo(e,t,r,n){let i=w(),o=N.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function co(e,t="daily"){let r=w(),n=N.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function po(e){let t=w(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function Vt(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ht(e)})}function sF(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Je()})}function lo(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ut(e)})}function fF(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return uo(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function hF(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>co(e,t)})}function vF(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await po(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function fo(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Je(e,t)})}function Ye(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,c=typeof a=="string"?parseFloat(a):a;return s+=c.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var jt=class{constructor(t){A(this,"symbol");A(this,"name");A(this,"icon");A(this,"precision");A(this,"stakingEnabled");A(this,"delegationEnabled");A(this,"balance");A(this,"stake");A(this,"stakedBalance");A(this,"delegationsIn");A(this,"delegationsOut");A(this,"usdValue");A(this,"hasDelegations",()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false);A(this,"delegations",()=>this.hasDelegations()?`(${Ye(this.stake,{fractionDigits:this.precision})} + ${Ye(this.delegationsIn,{fractionDigits:this.precision})} - ${Ye(this.delegationsOut,{fractionDigits:this.precision})})`:"");A(this,"staked",()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():Ye(this.stakedBalance,{fractionDigits:this.precision}):"-");A(this,"balanced",()=>this.balance<1e-4?this.balance.toString():Ye(this.balance,{fractionDigits:this.precision}));this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}};function qF(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await Ht(e),i=await Ut(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),c=[...s,...a.length?await Je(void 0,a):[]];return n.map(p=>{let l=i.find(x=>x.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=c.find(x=>x.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),S=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new jt({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:S})})},enabled:!!e})}function mo(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Nt(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(lo([t])),s=await r.ensureQueryData(Vt(e)),a=await r.ensureQueryData(fo(void 0,t)),c=o?.find(x=>x.symbol===t),p=s?.find(x=>x.symbol===t),f=+(a?.find(x=>x.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),S=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&S.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:S}}})}function mt(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function go(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(mt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(mt(e).queryKey)?.points??0)})})}function YF(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function cq(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await ao(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=eo(e,i,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let x=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(x){let P=Math.abs(Number.parseFloat(x[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:P}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:P}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:P});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Nt(e));else if(t==="HP")l=await o(ro(e));else if(t==="HBD")l=await o(to(e));else if(t==="POINTS")l=await o(go(e));else if((await n.ensureQueryData(Vt(e))).some(m=>m.symbol===t))l=await o(mo(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var id=(P=>(P.Transfer="transfer",P.TransferToSavings="transfer-saving",P.WithdrawFromSavings="withdraw-saving",P.Delegate="delegate",P.PowerUp="power-up",P.PowerDown="power-down",P.WithdrawRoutes="withdraw-routes",P.ClaimInterest="claim-interest",P.Swap="swap",P.Convert="convert",P.Gift="gift",P.Promote="promote",P.Claim="claim",P.Buy="buy",P.Stake="stake",P.Unstake="unstake",P.Undelegate="undelegate",P))(id||{});function gq(e,t,r){return v(["wallet","transfer"],e,n=>[Ne(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function bq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ge(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function xq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[ct(e,n.delegatee,n.vestingShares)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Tq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[pt(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await k(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function Iq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Nq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[We(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function jq(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Qe(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function zq(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[at(e,n.to,n.amount)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function eI(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ut(e,n.vestingShares)],async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function oI(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?_r(e,n.amount,n.requestId):lt(e,n.amount,n.requestId)],async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function pI(e,t,r){return v(["wallet","claim-interest"],e,n=>st(e,n.to,n.amount,n.memo,n.requestId),async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var od=5e3,Lt=new Map;function gI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Dr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],u.assets.hiveGeneralInfo(e),u.assets.hbdGeneralInfo(e),u.assets.hivePowerGeneralInfo(e)],o=Lt.get(n);o&&(clearTimeout(o),Lt.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Lt.delete(n);}},od);Lt.set(n,s);},t,"posting",{broadcastMode:r})}function _I(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function SI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function RI(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function DI(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function NI(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await k(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function sd(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Ne(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Qe(n,i,o,s,a)];case "power-up":return [at(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Ne(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Qe(n,i,o,s,a)];case "claim-interest":return st(n,i,o,s,a);case "convert":return [lt(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ut(n,o)];case "delegate":return [ct(n,i,o)];case "withdraw-routes":return [pt(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ge(n,i,o,s)];break}return null}function ad(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [He(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [He(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [He(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [He(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [He(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [br(n,[e])]}return null}function ud(e){return e==="claim"?"posting":"active"}function LI(e,t,r,n,i){let{mutateAsync:o}=ze.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=sd(t,r,s);if(a)return a;let c=ad(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,ud(r),{broadcastMode:i})}function zI(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[vr(e,n,i)],async(n,i)=>{await k(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),u.resourceCredits.account(e),u.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function ZI(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[Or(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function nD(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[xr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function pd(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function cD(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await re("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(pd),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function pD(e,t,r,n="vests",i="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await re("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function lD(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await re("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var ld=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(ld||{});async function fd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await w()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function wD(e,t,r,n){let{mutateAsync:i}=ze.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>fd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(mt(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var ho=/(^|\s)author:([^\s]+)/g,wo=/(^|\s)type:([^\s]+)/g,_o=/(^|\s)category:([^\s]+)/g,bo=/(^|\s)tag:([^\s]+)/g;var Ao=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Ao||{}),bD=5,vD=100;function Po(e){return e.trim().split(/\s+/)[0]??""}function md(e){return Po(e).replace(/^@+/,"").toLowerCase()}function gd(e){return Po(e).replace(/^#+/,"").toLowerCase()}function yd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function AD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=md(t),a=gd(n),c=yd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),c.length>0&&p.push(`tag:${c.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:c}}var vo=class{constructor(t){A(this,"query","");A(this,"search","");A(this,"author","");A(this,"type","");A(this,"category","");A(this,"tags",[]);A(this,"grab",t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""});A(this,"grabAuthor",()=>{this.author=this.grab(ho);});A(this,"grabType",()=>{let t=this.grab(wo);Object.values(Ao).includes(t)&&(this.type=t);});A(this,"grabCategory",()=>{this.category=this.grab(_o);});A(this,"grabTags",()=>{let t=new Set;this.tags=[...this.query.matchAll(bo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));});A(this,"grabSearch",()=>{for([ho,wo,_o,bo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();});this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}};async function Pe(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Ce(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var wd=isServer?0:3;function gt(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let c=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:be(ve,s)});return Pe(c,Ce)},retry:gt})}function ID(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:c,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:be(ve,i)});return Pe(y,Ce)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:gt})}async function MD(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await w()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:be(ve,s)});return Pe(p,Ce)}async function Oo(e,t,r=ve){let i=await w()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:be(r,t)});return Pe(i,Ce)}async function ND(e,t){let n=await w()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:be(ve,t)}),i=await Pe(n,Array.isArray);return i?.length>0?i:[e]}var Ad=4368*60*60*1e3,Pd=4,Od=3e3,xd=2e3,Ed=4e3,jD=2;function Sd(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function kd(e){let t=5381;for(let r=0;r>>0).toString(36)}function LD(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Sd(e.body??"",Od),o=kd(`${t}|${n.join(",")}|${i}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Ad).toISOString().slice(0,19),c=await Oo({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?xd:Ed),p=[],l=new Set;for(let f of c.results){if(p.length>=Pd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function YD(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Ft(n)},enabled:!!r})}function rK(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function uK(e,t,r,n,i,o){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),i!==void 0&&(c.votes=i),o&&(c.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(c),signal:be(ve,a)});return Pe(p,Ce)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:gt})}function dK(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function Id(e){let r=await w()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function yK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Id(t)},enabled:!!r&&!!t})}async function Bd(e,t){let n=await w()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Md(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function vK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Bd(t,i)},onSuccess(i){n&&Md(r,n,i);}})}function xK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function CK(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function qK(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function BK(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function HK(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function LK(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[Qr(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function zK(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Hr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function XK(e){let r=await w()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var Ld="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function rB(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Ld,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` -`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var iB=1.1,$d=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))($d||{});function oB(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function zd(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let c=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:c?{total_votes:c.total_votes??0,hive_hp:c.hive_hp,hive_proxied_hp:c.hive_proxied_hp,hive_hp_incl_proxied:c.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function pB(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?zn:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=w(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return zd(o[0])}})}function fB(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** +import {useQuery,useInfiniteQuery,useMutation,QueryClient,queryOptions,infiniteQueryOptions,useQueryClient,isServer}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import pn from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import Yn from'hivesigner';var rn=Object.defineProperty;var Ro=(e,t,r)=>t in e?rn(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var wt=(e,t)=>{for(var r in t)rn(e,r,{get:t[r],enumerable:true});};var A=(e,t,r)=>Ro(e,typeof t!="symbol"?t+"":t,r);var bt=new ArrayBuffer(0),vt=null,At=null;function Fo(){return vt||(typeof TextEncoder<"u"?vt=new TextEncoder:vt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),vt}function nn(){return At||(typeof TextDecoder<"u"?At=new TextDecoder:At={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),At}var j=class j{constructor(t=j.DEFAULT_CAPACITY,r=j.DEFAULT_ENDIAN){A(this,"buffer");A(this,"view");A(this,"offset");A(this,"markedOffset");A(this,"limit");A(this,"littleEndian");A(this,"readUInt32",this.readUint32);this.buffer=t===0?bt:new ArrayBuffer(t),this.view=t===0?new DataView(bt):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new j(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new j(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(bt));else if(Array.isArray(t))n=new j(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof j?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new j(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new j(0,this.littleEndian);let n=r-t,i=new j(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?bt:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=Fo().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=nn().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=nn().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};A(j,"LITTLE_ENDIAN",true),A(j,"BIG_ENDIAN",false),A(j,"DEFAULT_CAPACITY",16),A(j,"DEFAULT_ENDIAN",j.BIG_ENDIAN);var D=j;var S={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},Yt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Xt=e=>{let t=Yt(e);t.length&&(S.nodes=t);},Zt=e=>{let t=Yt(e);t.length&&(S.restNodes=t);},er=e=>{if(!e||typeof e!="object")return;let t={...S.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=Yt(n);i.length?t[r]=i:delete t[r];}S.restNodesByApi=t;},tr=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(S.userAgent=t);},rr=e=>{if(!e||typeof e!="object")return;let t=S.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var xe=class e{constructor(t,r,n){A(this,"data");A(this,"recovery");A(this,"compressed");this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new X(n.recoverPublicKey(t).toBytes())}};var X=class e{constructor(t,r){A(this,"key");A(this,"prefix");this.key=t,this.prefix=r??S.address_prefix;}static fromString(t){let r=S.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=pn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=ripemd160(o).subarray(0,4);if(!Io(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=xe.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return qo(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},qo=(e,t)=>{let r=ripemd160(e);return t+pn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},Io=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},w=(e,t)=>{e.writeVString(t);},Bo=(e,t)=>{e.writeInt16(t);},dn=(e,t)=>{e.writeInt64(t);},ln=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},Z=(e,t)=>{e.writeUint32(t);},fn=(e,t)=>{e.writeUint64(t);},_e=(e,t)=>{e.writeByte(t?1:0);},mn=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},I=(e,t)=>{let r=Pt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},Ee=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},ge=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(X.from(t).key);},gn=(e=null)=>(t,r)=>{r=Ot.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},yn=gn(),nr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},L=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},Fe=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},z=le([["weight_threshold",Z],["account_auths",nr(w,pe)],["key_auths",nr(ge,pe)]]),No=le([["account",w],["weight",pe]]),ir=le([["base",I],["quote",I]]),Mo=le([["account_creation_fee",I],["maximum_block_size",Z],["hbd_interest_rate",pe]]),F=(e,t)=>{let r=le(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},C={};C.account_create=F(R.account_create,[["fee",I],["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",w]]);C.account_create_with_delegation=F(R.account_create_with_delegation,[["fee",I],["delegation",I],["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",w],["extensions",L(se)]]);C.account_update=F(R.account_update,[["account",w],["owner",Fe(z)],["active",Fe(z)],["posting",Fe(z)],["memo_key",ge],["json_metadata",w]]);C.account_witness_proxy=F(R.account_witness_proxy,[["account",w],["proxy",w]]);C.account_witness_vote=F(R.account_witness_vote,[["account",w],["witness",w],["approve",_e]]);C.cancel_transfer_from_savings=F(R.cancel_transfer_from_savings,[["from",w],["request_id",Z]]);C.change_recovery_account=F(R.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",L(se)]]);C.claim_account=F(R.claim_account,[["creator",w],["fee",I],["extensions",L(se)]]);C.claim_reward_balance=F(R.claim_reward_balance,[["account",w],["reward_hive",I],["reward_hbd",I],["reward_vests",I]]);C.comment=F(R.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);C.comment_options=F(R.comment_options,[["author",w],["permlink",w],["max_accepted_payout",I],["percent_hbd",pe],["allow_votes",_e],["allow_curation_rewards",_e],["extensions",L(mn([le([["beneficiaries",L(No)]])]))]]);C.convert=F(R.convert,[["owner",w],["requestid",Z],["amount",I]]);C.create_claimed_account=F(R.create_claimed_account,[["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",ge],["json_metadata",w],["extensions",L(se)]]);C.custom=F(R.custom,[["required_auths",L(w)],["id",pe],["data",yn]]);C.custom_json=F(R.custom_json,[["required_auths",L(w)],["required_posting_auths",L(w)],["id",w],["json",w]]);C.decline_voting_rights=F(R.decline_voting_rights,[["account",w],["decline",_e]]);C.delegate_vesting_shares=F(R.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",I]]);C.delete_comment=F(R.delete_comment,[["author",w],["permlink",w]]);C.escrow_approve=F(R.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Z],["approve",_e]]);C.escrow_dispute=F(R.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Z]]);C.escrow_release=F(R.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",Z],["hbd_amount",I],["hive_amount",I]]);C.escrow_transfer=F(R.escrow_transfer,[["from",w],["to",w],["hbd_amount",I],["hive_amount",I],["escrow_id",Z],["agent",w],["fee",I],["json_meta",w],["ratification_deadline",Ee],["escrow_expiration",Ee]]);C.feed_publish=F(R.feed_publish,[["publisher",w],["exchange_rate",ir]]);C.limit_order_cancel=F(R.limit_order_cancel,[["owner",w],["orderid",Z]]);C.limit_order_create=F(R.limit_order_create,[["owner",w],["orderid",Z],["amount_to_sell",I],["min_to_receive",I],["fill_or_kill",_e],["expiration",Ee]]);C.limit_order_create2=F(R.limit_order_create2,[["owner",w],["orderid",Z],["amount_to_sell",I],["exchange_rate",ir],["fill_or_kill",_e],["expiration",Ee]]);C.recover_account=F(R.recover_account,[["account_to_recover",w],["new_owner_authority",z],["recent_owner_authority",z],["extensions",L(se)]]);C.request_account_recovery=F(R.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",z],["extensions",L(se)]]);C.reset_account=F(R.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",z]]);C.set_reset_account=F(R.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);C.set_withdraw_vesting_route=F(R.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",pe],["auto_vest",_e]]);C.transfer=F(R.transfer,[["from",w],["to",w],["amount",I],["memo",w]]);C.transfer_from_savings=F(R.transfer_from_savings,[["from",w],["request_id",Z],["to",w],["amount",I],["memo",w]]);C.transfer_to_savings=F(R.transfer_to_savings,[["from",w],["to",w],["amount",I],["memo",w]]);C.transfer_to_vesting=F(R.transfer_to_vesting,[["from",w],["to",w],["amount",I]]);C.vote=F(R.vote,[["voter",w],["author",w],["permlink",w],["weight",Bo]]);C.withdraw_vesting=F(R.withdraw_vesting,[["account",w],["vesting_shares",I]]);C.witness_update=F(R.witness_update,[["owner",w],["url",w],["block_signing_key",ge],["props",Mo],["fee",I]]);C.witness_set_properties=F(R.witness_set_properties,[["owner",w],["props",nr(w,yn)],["extensions",L(se)]]);C.account_update2=F(R.account_update2,[["account",w],["owner",Fe(z)],["active",Fe(z)],["posting",Fe(z)],["memo_key",Fe(ge)],["json_metadata",w],["posting_json_metadata",w],["extensions",L(se)]]);C.create_proposal=F(R.create_proposal,[["creator",w],["receiver",w],["start_date",Ee],["end_date",Ee],["daily_pay",I],["subject",w],["permlink",w],["extensions",L(se)]]);C.update_proposal_votes=F(R.update_proposal_votes,[["voter",w],["proposal_ids",L(dn)],["approve",_e],["extensions",L(se)]]);C.remove_proposal=F(R.remove_proposal,[["proposal_owner",w],["proposal_ids",L(dn)],["extensions",L(se)]]);var Qo=le([["end_date",Ee]]);C.update_proposal=F(R.update_proposal,[["proposal_id",fn],["creator",w],["daily_pay",I],["subject",w],["permlink",w],["extensions",L(mn([se,Qo]))]]);C.collateralized_convert=F(R.collateralized_convert,[["owner",w],["requestid",Z],["amount",I]]);C.recurrent_transfer=F(R.recurrent_transfer,[["from",w],["to",w],["amount",I],["memo",w],["recurrence",pe],["executions",pe],["extensions",L(le([["type",ln],["value",le([["pair_id",ln]])]]))]]);var Ho=(e,t)=>{let r=C[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},Uo=le([["ref_block_num",pe],["ref_block_prefix",Z],["expiration",Ee],["operations",L(Ho)],["extensions",L(w)]]),Vo=le([["from",ge],["to",ge],["nonce",fn],["check",Z],["encrypted",gn()]]),de={Asset:I,Memo:Vo,Price:ir,PublicKey:ge,String:w,Transaction:Uo,UInt16:pe,UInt32:Z};var nt=e=>new Promise(t=>setTimeout(t,e));var jo=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function bn(){return jo?{"User-Agent":S.userAgent}:{}}var ee=class extends Error{constructor(r){super(r.message);A(this,"name","RPCError");A(this,"data");A(this,"code");A(this,"stack");this.code=r.code,"data"in r&&(this.data=r.data);}},qe=class extends Error{constructor(r,n,i={}){super(n);A(this,"node");A(this,"rateLimitMs");A(this,"isRateLimit");this.node=r,this.rateLimitMs=i.rateLimitMs??0,this.isRateLimit=i.isRateLimit??false;}};function vn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Lo=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],$o=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Wo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function Go(e){if(!e)return false;if(e instanceof qe)return true;if(e instanceof ee)return false;let t=Wo(e);return !!(Lo.some(r=>t.includes(r))||$o.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function or(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function An(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var zo=1e4,Jo=6e4,Yo=12e4,hn=2,_n=6e4,wn=12e4,Xo=30,it=.3,sr=3,ot=5*6e4,Pn=6e4,On=1e3,xn=2e3,Et=class{constructor(){A(this,"health",new Map);}getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=sr&&i-o.updatedAt<=ot?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>ot&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:it*r+(1-it)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>ot?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=it*r+(1-it)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=hn&&(o.cooldownUntil=i+_n),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,hn),o.lastFailureTime=i,o.cooldownUntil=i+_n,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>Yo&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(zo*2**n.rateLimitStreak,Jo);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=wn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=wn&&o-n.headBlock>Xo)}getOrderedNodes(t,r){let n=[],i=[];for(let u of t)this.isNodeHealthy(u,r)?n.push(u):i.push(u);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((u,p)=>({node:u,i:p,score:this.scoreNode(u,o)})).sort((u,p)=>u.score-p.score||u.i-p.i).map(u=>u.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(u=>u!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=sr&&r-t.latencyUpdatedAt<=ot}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:On}pickReprobeCandidate(t,r){let n=r-Pn,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),u=Math.max(a.latencyUpdatedAt,a.lastProbeAt);u<=n&&u=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(S.resilience.hedgeBucketCapacity,this.tokens+S.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>S.resilience.hedgeBucketCapacity&&(this.tokens=S.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=S.resilience.hedgeBucketCapacity){this.tokens=t;}},cr=new ar;function St(e,t,r,n,i){let o=S.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function ur(e,t,r,n){r instanceof qe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof ee?e.recordFailure(t,n):e.recordFailure(t);}function En(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function Zo(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function Sn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Zo()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function pr(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var st=async(e,t,r,n=S.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:u,cleanup:p}=Sn(n),{signal:l,cleanup:f}=pr(u,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...bn()},signal:l});if(y.status===429)throw new qe(e,"HTTP 429 Rate Limited",{rateLimitMs:vn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new qe(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let x=h.error;throw "message"in x&&"code"in x?new ee(x):h.error}throw h}catch(y){if(y instanceof ee||y instanceof qe||o?.aborted)throw y;if(i)return st(e,t,r,n,false,o);throw y}finally{m();}};function xt(){return nt(50+Math.random()*50)}function es(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:u,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,x=0,E=false,P=false,O,W,V=0,N=[],H=Y=>{if(!h){h=true,W!==void 0&&(clearTimeout(W),W=void 0);for(let q of N)q.signal.aborted||q.abort();Y();}},G=(Y,q)=>{x++;let me=new AbortController;N.push(me);let rt=pr(me.signal,p),To=St($,Y,t,s,a),Jt=Date.now();q||(V=Jt),st(Y,t,r,To,false,rt.signal).then(oe=>{if(rt.cleanup(),x--,q||(P=true),!h){if(f&&!f(oe)){if($.recordDefectiveResponse(Y,n),O=new Error(`[hive-tx] response validation failed for ${t} from ${Y}`),!q&&!E){H(()=>y(O));return}x===0&&H(()=>y(O));return}$.recordSuccess(Y,n,Date.now()-Jt,t),En($,Y,t,oe),q?P||$.recordCensoredLatency(i,Date.now()-V,t):E||cr.refill(),H(()=>m(oe));}}).catch(oe=>{if(rt.cleanup(),x--,q||(P=true),!h){if(p?.aborted){H(()=>y(oe));return}if(oe instanceof ee&&!or(oe.code,oe.message)){H(()=>y(oe));return}if(ur($,Y,oe,n),$.recordSlowFailure(Y,Date.now()-Jt,t),O=oe,!q&&!E){H(()=>y(oe));return}x===0&&H(()=>y(O));}});};G(i,false);let Re=$.getUsableLatencyMs(i,t)??0,tt=St($,i,t,s,a),zt=Math.min(Math.max(S.resilience.hedgeDelayFloorMs,S.resilience.hedgeDelayFactor*Re),.8*tt);W=setTimeout(()=>{if(W=void 0,h||p?.aborted||Date.now()>=u)return;let Y=o.filter(me=>$.isNodeHealthy(me,n));if(Y.length===0)return;let q=Y[Math.floor(Math.random()*Y.length)];cr.trySpend()&&(E=true,l(q),G(q,true));},zt);})}var g=async(e,t=[],r,n=S.retry,i,o)=>{if(!Array.isArray(S.nodes))throw new Error("config.nodes is not an array");if(S.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??S.timeout,u=An(e),p=Date.now()+S.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=$.getOrderedNodes(S.nodes,u),h=y.find(P=>!l.has(P));h||(l.clear(),h=y[0]),l.add(h);let x=[];if(S.resilience.hedge&&$.getUsableLatencyMs(h,e)!==void 0&&(x=y.filter(P=>!l.has(P)&&$.isNodeHealthy(P,u)).slice(0,3)),x.length>0)try{return await es({method:e,params:t,api:u,primary:h,hedgePool:x,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:P=>l.add(P),validate:o})}catch(P){if(P instanceof ee&&!or(P.code,P.message)||i?.aborted)throw P;f=P,m{if(!Array.isArray(S.nodes))throw new Error("config.nodes is not an array");if(S.nodes.length===0)throw new Error("config.nodes is empty");let i=An(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await st(p,e,t,r,!1,n);return $.recordSuccess(p,i),l}catch(l){if(l instanceof ee||n?.aborted||(ur($,p,l,i),s=l,!Go(l)))throw l}}throw s},ts={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function re(e,t,r,n,i=S.retry,o){if(!Array.isArray(S.restNodes))throw new Error("config.restNodes is not an array");if(S.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??S.timeout,u=Date.now()+S.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=S.restNodesByApi?.[e]?.length?S.restNodesByApi[e]:S.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=u);h++){let x=Se.getOrderedNodes(l,e),E=x.find(q=>!f.has(q));E||(f.clear(),E=x[0]),f.add(E);let P=E+ts[e],O=t,W=r||{},V=new Set;Object.entries(W).forEach(([q,me])=>{O.includes(`{${q}}`)&&(O=O.replace(`{${q}}`,encodeURIComponent(String(me))),V.add(q));});let N=new URL(P+O);if(Object.entries(W).forEach(([q,me])=>{V.has(q)||(Array.isArray(me)?me.forEach(rt=>N.searchParams.append(q,String(rt))):N.searchParams.set(q,String(me)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:H,cleanup:G}=Sn(St(Se,E,p,a,s)),{signal:Re,cleanup:tt}=pr(H,o),zt=()=>{G(),tt();},Y=Date.now();try{let q=await fetch(N.toString(),{signal:Re,headers:bn()});if(q.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(q.status===429)throw Se.recordRateLimit(E,vn(q.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${E}`);if(q.status===503)throw Se.recordFailure(E,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${E}`);if(!q.ok)throw Se.recordFailure(E,e),y=!0,new Error(`HTTP ${q.status} from ${E}`);return Se.recordSuccess(E,e,Date.now()-Y,p),q.json()}catch(q){if(q?.message?.includes("HTTP 404")||o?.aborted)throw q;y||Se.recordFailure(E,e),Se.recordSlowFailure(E,Date.now()-Y,p),m=q,h{if(!Array.isArray(S.nodes))throw new Error("config.nodes is not an Array");if(r>S.nodes.length)throw new Error("quorum > config.nodes.length");let o=(u=>{let p=[...u];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(S.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let u=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=rs(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function rs(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var is=hexToBytes(S.chain_id),Ie=class e{constructor(t){A(this,"transaction");A(this,"expiration",6e4);A(this,"txId");A(this,"createTransaction",async t=>{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};});t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Ve("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof ee&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await nt(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return xe.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new X(secp256k1.getPublicKey(this.key),t)}toString(){return as(new Uint8Array([...qn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},In=e=>sha256(sha256(e)),as=e=>{let t=In(e);return pn.encode(new Uint8Array([...e,...t.slice(0,4)]))},cs=e=>{let t=pn.decode(e);if(!Rn(t.slice(0,1),qn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=In(n).slice(0,4);if(!Rn(r,i))throw new Error("Private key checksum mismatch");return n},Rn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nNn(e,t,n,r),Bn=(e,t,r,n,i)=>Nn(e,t,r,n,i).message,Nn=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let u=sha512(new Uint8Array(a.toBuffer())),p=u.subarray(32,48),l=u.subarray(0,32),f=sha256(u).subarray(0,4),m=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=ds(n,l,p);}else n=fs(n,l,p);return {nonce:o,message:n,checksum:y}},ds=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},fs=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},dr=null,ms=()=>{if(dr===null){let r=secp256k1.utils.randomSecretKey();dr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++dr%65536;return e=e<{let t=bs(e,33);return new X(t)},ys=e=>e.readUint64(),hs=e=>e.readUint32(),_s=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},ws=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function bs(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var vs=ws([["from",Mn],["to",Mn],["nonce",ys],["check",hs],["encrypted",_s]]),Qn={Memo:vs};var Un=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),jn(),e=Ln(e),t=As(t);let i=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:u}=Kn(e,t,o,n),p=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);de.Memo(p,{check:u,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+pn.encode(l)},Vn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),jn(),e=Ln(e);let r=Qn.Memo(pn.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new X(n.key).toString()?new X(i.key):new X(n.key);r=Bn(e,p,o,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Ct,jn=()=>{if(Ct===void 0){let e;Ct=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Un(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Vn(t,n);}finally{Ct=e==="#memo\u7231";}}if(Ct===false)throw new Error("This environment does not support encryption.")},Ln=e=>typeof e=="string"?U.fromString(e):e,As=e=>typeof e=="string"?X.fromString(e):e,$n={decode:Vn,encode:Un};var ie={};wt(ie,{buildWitnessSetProperties:()=>ks,makeBitMaskFilter:()=>Es,operations:()=>xs,validateUsername:()=>Os});var Os=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(Ss,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),Ss=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=de.UInt32;break;case "hbd_interest_rate":i=de.UInt16;break;case "url":i=de.String;break;case "hbd_exchange_rate":i=de.Price;break;case "account_creation_fee":i=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,Cs(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},Cs=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function Im(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function Wn(e){try{return U.fromString(e),!0}catch{return false}}async function te(e,t){let r=new Ie;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Ve("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Gn(e,t){let r=new Ie;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var Rs=432e3;function zn(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/Rs,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function Fs(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function fr(e){let t=Fs(e)*1e6;return zn(t,e.voting_manabar)}function Tt(e){return zn(Number(e.max_rc),e.rc_manabar)}var Jn=(u=>(u.COMMON="common",u.INFO="info",u.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",u.MISSING_AUTHORITY="missing_authority",u.TOKEN_EXPIRED="token_expired",u.NETWORK="network",u.TIMEOUT="timeout",u.VALIDATION="validation",u))(Jn||{});function je(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function qs(e){let t=je(e);return [t.message,t.type]}function we(e){let{type:t}=je(e);return t==="missing_authority"||t==="token_expired"}function Is(e){let{type:t}=je(e);return t==="insufficient_resource_credits"}function Ds(e){let{type:t}=je(e);return t==="info"}function Ks(e){let{type:t}=je(e);return t==="network"||t==="timeout"}async function be(e,t,r,n,i="posting",o,s,a="async"){let u=n?.adapter;switch(e){case "key":{if(!u)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(u.getOwnerKey)p=await u.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":u.getActiveKey&&(p=await u.getActiveKey(t));break;case "memo":if(u.getMemoKey)p=await u.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await u.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=U.fromString(p);return a==="async"?await Gn(r,l):await te(r,l)}case "hiveauth":{if(!u?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await u.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!u)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await u.getAccessToken(t);if(p)try{return (await new Yn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(u.broadcastWithHiveSigner&&we(l))return await u.broadcastWithHiveSigner(t,r,i);throw l}if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!u?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await u.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Ns(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await be("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await be("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await be("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await be(l,e,t,r,n,void 0,void 0,i)}catch(m){if(we(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await be(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await be("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(we(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await be(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await be(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let x;switch(n){case "owner":o.getOwnerKey&&(x=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(x=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(x=await o.getMemoKey(e));break;default:x=await o.getPostingKey(e);break}x?y=x:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let x=await o.getAccessToken(e);x&&(h=x);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await be(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!we(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async u=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(u);try{if(i?.enableFallback!==!1&&i?.adapter)return await Ns(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=U.fromString(l);return await te(p,m)}let f=i?.accessToken;if(f)return (await new Yn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof ee?new Error(l.message):l}}})}async function Xn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let u=U.fromString(o);return te([["custom_json",i]],u)}let s=n?.accessToken;if(s)return (await new Yn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let u=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,u,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,u,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Jm=4e3;function k(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function ve(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var De=(()=>{try{return !1}catch{return false}})(),Hs=()=>{try{return ""}catch{return}},Ae=1e4,Zn=120*1e3,Rt,Us;function Vs(){return Rt?Rt():Us??(Us=new QueryClient)}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return S.nodes},heliusApiKey:Hs(),get queryClient(){return Vs()},set queryClient(e){Rt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},M;(P=>{function e(O){d.queryClient=O;}P.setQueryClient=e;function t(O){Rt=O;}P.setQueryClientResolver=t;function r(O){d.privateApiHost=O;}P.setPrivateApiHost=r;function n(O){d.clientId=O;}P.setClientId=n;function i(O){if(typeof O!="string"||O.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=O;}P.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}P.getValidatedBaseUrl=o;function s(O){d.pollsApiHost=O;}P.setPollsApiHost=s;function a(O){d.imageHost=O;}P.setImageHost=a;function u(O){Xt(O);}P.setHiveNodes=u;function p(O){Zt(O);}P.setRestNodes=p;function l(O){er(O);}P.setRestNodesByApi=l;function f(O){tr(O);}P.setUserAgent=f;function m(O){rr(O);}P.setResilience=m;function y(O){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(O))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(O))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(O))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(O)||/\.\+\.\+/.test(O))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let W=/\.?\{(\d+),(\d+)\}/g,V;for(;(V=W.exec(O))!==null;){let[,N,H]=V;if(parseInt(H,10)-parseInt(N,10)>1e3)return {safe:false,reason:`excessive range: {${N},${H}}`}}return {safe:true}}function h(O){let W=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],V=5;for(let N of W){let H=Date.now();try{O.test(N);let G=Date.now()-H;if(G>V)return {safe:!1,reason:`runtime test exceeded ${V}ms (took ${G}ms on input length ${N.length})`}}catch(G){return {safe:false,reason:`runtime test threw error: ${G}`}}}return {safe:true}}function x(O,W=200){try{if(!O)return De&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(O.length>W)return De&&console.warn(`[SDK] DMCA pattern rejected: length ${O.length} exceeds max ${W} - pattern: ${O.substring(0,50)}...`),null;let V=y(O);if(!V.safe)return De&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${V.reason}) - pattern: ${O.substring(0,50)}...`),null;let N;try{N=new RegExp(O);}catch(G){return De&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${O.substring(0,50)}...`,G),null}let H=h(N);return H.safe?N:(De&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${H.reason}) - pattern: ${O.substring(0,50)}...`),null)}catch(V){return De&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${O.substring(0,50)}...`,V),null}}function E(O={}){let W=G=>Array.isArray(G)?G.filter(Re=>typeof Re=="string"):[],V=O||{},N={accounts:W(V.accounts),tags:W(V.tags),patterns:W(V.posts)};d.dmcaAccounts=N.accounts,d.dmcaTags=N.tags,d.dmcaPatterns=N.patterns,d.dmcaTagRegexes=N.tags.map(G=>x(G)).filter(G=>G!==null),d.dmcaPatternRegexes=[];let H=N.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&De&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${N.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${N.tags.length} compiled (${H} rejected)`),console.log(` - Post patterns: ${N.patterns.length} (using exact string matching)`),H>0&&console.warn(`[SDK] ${H} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}P.setDmcaLists=E;})(M||(M={}));function cg(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,ei;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(ei||(ei={}));function pg(e){return btoa(JSON.stringify(e))}function lg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var ti=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(ti||{}),Ft=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Ft||{});function T(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:ti[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Ft[e.nai]}}var mr;function _(){if(!mr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");mr=globalThis.fetch.bind(globalThis);}return mr}function ri(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Ws(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function ae(e,t){return Ws(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Le(e,t){return e/1e6*t}function ni(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var ii=60*1e3;function Pe(){return queryOptions({queryKey:c.core.dynamicProps(),refetchInterval:ii,staleTime:ii,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=T(t.total_vesting_shares).amount,a=T(t.total_vesting_fund_hive).amount,u=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(u=a/s*1e6);let p=T(r.current_median_history.base).amount,l=T(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=T(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",x=Number(i.content_constant??0),E=String(o.current_hardfork_version??"0.0.0"),P=Number(o.last_hardfork??0),O=t.hbd_print_rate,W=t.hbd_interest_rate,V=t.head_block_number,N=a,H=s,G=T(t.virtual_supply).amount,Re=t.vesting_reward_percent||0,tt=n.account_creation_fee;return {hivePerMVests:u,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:x,currentHardforkVersion:E,lastHardfork:P,hbdPrintRate:O,hbdInterestRate:W,headBlock:V,totalVestingFund:N,totalVestingShares:H,virtualSupply:G,vestingRewardPercent:Re,accountCreationFee:tt,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function Sg(e="post"){return queryOptions({queryKey:c.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function Ke(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var c={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>Ke("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Ke("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Ke("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Ke("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>Ke("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>Ke("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>Ke("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"],resourceParams:()=>["resource-credits","resource-params"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function gr(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=0;for(let r=0;r=55296&&n<=56319&&r+1>>=7;while(r>0);return t}function qg(e){return queryOptions({queryKey:c.ai.prices(),queryFn:async()=>{let r=await _()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function Bg(e,t){return queryOptions({queryKey:c.ai.assistPrices(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function Hg(e,t){return queryOptions({queryKey:c.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function ea(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Lg(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??ea()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let u=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw u.status=i.status,u.data=a,u}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:c.points._prefix(e)});}})}function ra(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function zg(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:ra()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.assistPrices(e)}));}})}function ia(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Zg(e,t){return useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??ia()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),u={};try{u=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:u})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.transcribePrice(e)}));}})}function yr(e){return !e.posting_json_metadata&&!e.json_metadata}function sa(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function Q(e){return queryOptions({queryKey:c.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(yr(i)&&sa(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!yr(l[0])));if(p[0]&&!yr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=Be(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,u=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:u,profile:o}},enabled:!!e,staleTime:6e4})}var aa=new Set(["__proto__","constructor","prototype"]);function qt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function oi(e,t){let r={...e};for(let n of Object.keys(t)){if(aa.has(n))continue;let i=t[n],o=r[n];qt(i)&&qt(o)?r[n]=oi(o,i):r[n]=i;}return r}function ca(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function Be(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function si(e){return Be(e?.posting_json_metadata)}function ai(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Be(e.posting_json_metadata)).length;return Object.keys(Be(t.posting_json_metadata)).length>r?t:e}function ua(e){if(!e)return {};try{let t=JSON.parse(e);if(qt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ci({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=ua(e),i=qt(n.profile)?n.profile:{},o=hr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function hr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=oi(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=ca(s.tokens),s.version=2,s}function It(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Be(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function pa(e){return new TextEncoder().encode(e).length}function We(e){return e?pa(e)<=16:false}function gy(e){return queryOptions({queryKey:c.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(We);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return It(r??[])}})}function by(e){return queryOptions({queryKey:c.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function xy(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function Ty(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var ui=1e3,ya=20;function Dy(e){return queryOptions({queryKey:c.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthWe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function $y(e,t=5,r=[]){return queryOptions({queryKey:c.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var ba=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Jy(e,t){return queryOptions({queryKey:c.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,u=typeof a.token=="string"?a.token:void 0;if(!u)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:u,currency:u,address:f,show:y,type:"CHAIN",meta:l},x=[];for(let[E,P]of Object.entries(p))typeof E=="string"&&(ba.has(E)||typeof P!="string"||!P||/^[A-Z0-9]{2,10}$/.test(E)&&x.push({symbol:E,currency:E,address:P,show:y,type:"CHAIN",meta:{address:P,show:y}}));return [h,...x]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function pi(e,t){return queryOptions({queryKey:c.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function oh(e){return queryOptions({queryKey:c.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function uh(e,t){return queryOptions({queryKey:c.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function ph(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function mh(e,t){return queryOptions({queryKey:c.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function gh(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function wh(e,t,r){return queryOptions({queryKey:c.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await _()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function Ph(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:c.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await _()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function kh(e){return queryOptions({enabled:!!e,queryKey:c.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function Ih(e,t=50){return queryOptions({queryKey:c.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!We(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var K=ie.operations,li={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.fill_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay]},Fa=Array.from(new Set(Object.values(li).flat()));function qa(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ia(e){return e.replace(/_operation$/,"")}function Da(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function Ka(e){if(!Da(e))return e;let t=T(e),r=Ft[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Ba(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Ka(n);return t}function Uh(e,t=20,r=""){let n=r?li[r]:Fa;return infiniteQueryOptions({queryKey:c.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await re("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ia(m.op.type);return {...Ba(m.op.value),num:qa(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),u=await s(i),p=a(u),l=i??u.total_pages;if(i===null&&p.length1)try{let f=await s(u.total_pages-1);p=[...p,...a(f)],l=u.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function $h(){return queryOptions({queryKey:c.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Jh(e){return infiniteQueryOptions({queryKey:c.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=M.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function e_(e){return queryOptions({queryKey:c.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function s_(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return infiniteQueryOptions({queryKey:c.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Va=30;function l_(e,t,r){return queryOptions({queryKey:c.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(u=>t==="following"?u.following:u.follower).filter(u=>u.toLowerCase().includes(r.toLowerCase())).slice(0,Va);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(u=>({name:u.name,full_name:u.metadata.profile?.name||"",reputation:u.reputation,active:u.active}))??[]}})}function y_(e=20){return infiniteQueryOptions({queryKey:c.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function A_(e=250){return infiniteQueryOptions({queryKey:c.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!ri(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Ge(e,t){return queryOptions({queryKey:c.posts.fragments(e),queryFn:async()=>t?(await _()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function E_(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function T_(e="feed"){return queryOptions({queryKey:c.posts.promoted(e),queryFn:async()=>{let t=M.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await _()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function D_(e){return queryOptions({queryKey:c.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Q_(e,t,r){return queryOptions({queryKey:c.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function L_(e,t){return queryOptions({queryKey:c.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function J_(e,t){return queryOptions({queryKey:c.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function tw(e,t){return queryOptions({queryKey:c.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function ne(e){return Array.isArray(e)?e.map(t=>di(t)):di(e)}function di(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function fi(e,t,r){try{let n=await kt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function mi(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return queryOptions({queryKey:c.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let u=await fi(e,i,r);if(!u)return null;let p=n!==void 0?{...u,num:n}:u;return ne(p)}let a=n!==void 0?{...s,num:n}:s;return ne(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ce(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function gi(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await tc(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function yi(e,t,r){let n=e.map(ct),i=await Promise.all(n.map(o=>gi(o,t,void 0,r)));return ne(i)}async function hi(e,t="",r="",n=20,i="",o="",s){let a=await ce("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?yi(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function _r(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ce("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?yi(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function ct(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function tc(e="",t="",r="",n,i){let o=await ce("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=ct(o),a=await gi(s,r,n,i);return ne(a)}}async function yw(e="",t=""){let r=await ce("get_post_header",{author:e,permlink:t});return r&&ct(r)}async function _i(e,t,r){let n=await ce("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=ct(s);return i}return n}async function wi(e,t=""){return ce("get_community",{name:e,observer:t})}async function hw(e="",t=100,r,n="rank",i=""){return ce("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function bi(e){let t=await ce("normalize_post",{post:e});return t&&ct(t)}async function _w(e){return ce("list_all_subscriptions",{account:e})}async function ww(e){return ce("list_subscribers",{community:e})}async function bw(e,t){return ce("get_relationship_between_accounts",[e,t])}async function Dt(e,t){return ce("get_profiles",{accounts:e,observer:t})}var Ai=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(Ai||{});function wr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function rc(e,t,r){let n=l=>wr(l.pending_payout_value).amount+wr(l.author_payout_value).amount+wr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[u];return u>=0&&(a.splice(u,1),a.unshift(p)),a}function Pi(e,t="created",r=true,n){let i=n||d.defaultObserver;return queryOptions({queryKey:c.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return ne(s)},enabled:r&&!!e,select:o=>rc(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),u=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!u.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function Sw(e,t,r,n=true){let i=r||d.defaultObserver;return queryOptions({queryKey:c.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>_i(e,t,i)})}function Iw(e,t="posts",r=20,n="",i=true){return infiniteQueryOptions({queryKey:c.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await _r(t,e,o.author??"",o.permlink??"",r,n,s);return ne(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Dw(e,t="posts",r="",n="",i=20,o="",s=true){return queryOptions({queryKey:c.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let u=await _r(t,e,r,n,i,o,a);return ne(u??[])}})}var Oi=new Map;function ac(e){let t=Oi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>cc(n,e))}),Oi.set(e,t)),t}function cc(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function Vw(e,t,r=20,n="",i=true,o={}){return infiniteQueryOptions({queryKey:c.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let u=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(u="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:u,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return ne(p)},select:ac(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function jw(e,t="",r="",n=20,i="",o="",s=true){return queryOptions({queryKey:c.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let u=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(u="");let p=await hi(e,t,r,n,u,o,a);return ne(p??[])}})}function zw(e,t,r=200){return queryOptions({queryKey:c.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function eb(e,t){return queryOptions({queryKey:c.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function ib(e,t){return queryOptions({queryKey:c.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function ob(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ub(e,t){return queryOptions({queryKey:c.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function pb(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Ei(e){let r=await _()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function mb(e,t){return queryOptions({queryKey:c.posts.images(e),queryFn:async()=>!e||!t?[]:Ei(t),enabled:!!e&&!!t})}function gb(e,t){return queryOptions({queryKey:c.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Ei(t),enabled:!!e&&!!t})}function yb(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return ae(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function bb(e,t,r=false){return queryOptions({queryKey:c.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function _c(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function Ob(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?_c(n,r):"";return queryOptions({queryKey:c.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:u,tags:p}=s.list[0];return {body:a,title:u,tags:p}},enabled:i})}function kb(e,t,r=true){return queryOptions({queryKey:c.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function bc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function vc(e){return {...e,id:e.id??e.post_id}}function ye(e,t){if(!e)return null;let r=e.container??e,n=bc(r,t),i=e.parent?vc(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function Ac(e){return Array.isArray(e)?e:[]}async function Si(e){let t=Pi(e,"created",true),r=await d.queryClient.fetchQuery(t),n=Ac(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function ki(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var xc=20;function Ci(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??xc}}async function Ti({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let u=M.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",u);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=ye(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function Kb(e={}){let t=Ci(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:c.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:u,signal:p})=>Ti(t,u,p),getNextPageParam:u=>{if(!(u.lengthTi(t,void 0,u)})}var Sc=20;function kc(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Sc}}async function Cc({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=M.getValidatedBaseUrl(),u=new URL("/private-api/waves/shorts",a);u.searchParams.set("limit",String(i)),o&&u.searchParams.set("cursor",o),e.forEach(f=>u.searchParams.append("container",f)),t&&u.searchParams.set("tag",t),r&&u.searchParams.set("author",r),n&&u.searchParams.set("observer",n);let p=await fetch(u.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=ye(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Ub(e={}){let t=kc(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return infiniteQueryOptions({queryKey:c.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:u})=>Cc(t,a,u),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of u){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Si(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:ki(f,l,e)}}let p=u[u.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function zb(e){return infiniteQueryOptions({queryKey:c.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await qc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Dc=40;function ev(e,t,r=Dc){return infiniteQueryOptions({queryKey:c.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>ye(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function ov(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>ye(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function uv(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:c.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:u,posts:p})=>({tag:u,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function mv(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>ye(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function _v(e){return queryOptions({queryKey:c.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=M.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function Pv(e,t=true){return queryOptions({queryKey:c.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>bi(e)})}function Uc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Ri(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function Rv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return infiniteQueryOptions({queryKey:c.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Ri(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(mi(m.author,m.permlink));Uc(y)&&l.push(y);}let[f]=a;return {lastDate:f?Ri(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function Kv(e,t,r=true){return queryOptions({queryKey:c.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Dt(e,t)})}function Uv(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:c.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await re("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function Wv(e,t="HIVE",r="yearly"){return queryOptions({queryKey:c.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await re("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Yv(){return queryOptions({queryKey:c.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function Xv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function iA(e,t,r){let n=useQueryClient(),{data:i}=useQuery(Q(e));return v(["accounts","update"],e,o=>{let s=ai(n.getQueryData(Q(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ci({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(Q(e).queryKey,a=>{if(!a)return a;let u=JSON.parse(JSON.stringify(a));return u.profile=hr({existingProfile:si(a),profile:s.profile,tokens:s.tokens}),u}),await k(t?.adapter,r,[c.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...Q(e),staleTime:0});}catch{}}})}function uA(e,t,r,n,i){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=pi(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await Xn(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(c.accounts.relations(e,t),o),t&&b().invalidateQueries(Q(t));}})}function br(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Ne(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function Me(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function vr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function Ar(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Qe(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Jc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Qe(e,o.trim(),r,n))}function Yc(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function ze(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function He(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function Fi(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function ut(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [He(e,t,r,n,i),Fi(e,i)]}function pt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function lt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function dt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function ft(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function mt(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function Pr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Ue(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function Or(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function xr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function Er(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function Kt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function Xc(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Zc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return Kt(e,t)}function Sr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function kr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function Cr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Tr(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function Rr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function eu(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function tu(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function Fr(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function qr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Ir(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Dr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Kr(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Br(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function ru(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function nu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var qi=(r=>(r.Buy="buy",r.Sell="sell",r))(qi||{}),Ii=(r=>(r.EMPTY="",r.SWAP="9",r))(Ii||{});function Nt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function Bt(e,t=3){return e.toFixed(t)}function iu(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,u=n==="buy"?`${Bt(t,3)} HBD`:`${Bt(t,3)} HIVE`,p=n==="buy"?`${Bt(r,3)} HIVE`:`${Bt(r,3)} HBD`;return Nt(e,u,p,false,s,a)}function Nr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Mr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function ou(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function su(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Qr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Hr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Ur(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Vr(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let u={...t,account_auths:a};return u.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:u,memo_key:i,json_metadata:o}]}function au(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function cu(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function uu(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function pu(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function jr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Lr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function $r(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Je(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function lu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>Je(e,o.trim(),r,n))}function Wr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function du(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function fu(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function TA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Er(e,n)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function IA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Kt(e,n)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function NA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function UA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function $A(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:n})}function YA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=c.accounts.favorites(e),a=c.accounts.favoritesInfinite(e),u=c.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:u})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(u);o.setQueryData(u,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(x=>({...x,data:x.data.filter(E=>E.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);s?.previousCheck!==void 0&&a.setQueryData(c.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function bu(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Di(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let u=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=bu(y,n.map((h,x)=>[h[p].createPublic().toString(),x+1])),l};return te([["account_update",{account:e,json_metadata:r.json_metadata,owner:u("owner"),active:u("active"),posting:u("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function aP(e,t){let{data:r}=useQuery(Q(e)),{mutateAsync:n}=Di(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,i,"owner"),active:U.fromLogin(e,i,"active"),posting:U.fromLogin(e,i,"posting"),memo_key:U.fromLogin(e,i,"memo")}]})},...t})}function fP(e,t,r){let n=useQueryClient(),{data:i}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let u=JSON.parse(JSON.stringify(i.posting));u.account_auths=u.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:u,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return te([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return t.hsCallbackUrl,Yn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(Q(e).queryKey,u=>({...u,posting:{...u?.posting,account_auths:u?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function bP(e,t,r,n){let{data:i}=useQuery(Q(e));return useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:u})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await _()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:u,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return te([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return r.hsCallbackUrl,Yn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function AP(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function Ki(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([u])=>!r.has(u.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function kP(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=Ki(r,o);return te([["account_update",s]],n)},...t})}function FP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Ur(n,i)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function KP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Vr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await k(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}function QP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Hr(e,n.newAccountName,n.keys):Qr(e,n.newAccountName,n.keys,n.fee)],async()=>{await k(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}var Gr=300*60*24,Fu=1e4,qu=5e7;function Bi(e){let t=T(e.vesting_shares).amount,r=T(e.received_vesting_shares).amount,n=T(e.delegated_vesting_shares).amount,i=T(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Iu(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Du(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function Ku(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=Bi(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Fu/(n*Gr)),a=fr(e),u=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(u)||s>u?0:Math.max(s-qu,0)}function Bu(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Du(t))return Ku(e,t,n);let i=0;try{if(i=Bi(e),!Number.isFinite(i))return 0}catch{return 0}return Iu(i,r,n)}function jP(e){return fr(e).percentage/100}function LP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*Gr/1e4}function $P(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/Gr;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function WP(e){return Tt(e).percentage/100}function GP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let u=Bu(e,t,r,n);return Number.isFinite(u)?u/i*o*(s/a):0}var Nu={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Mu(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Qu(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function Hu(e){let t=e[0];return t==="custom_json"?Mu(e):t==="create_proposal"||t==="update_proposal"?Qu(e):Nu[t]??"posting"}function JP(e){let t="posting";for(let r of e){let n=Hu(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function t0(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=U.fromLogin(e,r,"active"):Wn(r)?n=U.fromString(r):n=U.from(r),te([t],n)}})}function i0(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function c0(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Yn.sendOperation(t,{callback:e},()=>{})})}function d0(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ni(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Mi(e,t){return {...e??{},title:t.title,body:t.body}}function b0(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await _()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Mi(r,n);i.setQueryData(Ge(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,u)=>u===0?{...a,data:[o,...a.data]}:a)});}})}function S0(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ni(s,r,n);i.setQueryData(Ge(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(u=>u.id===n.fragmentId?o(u):u)}))});}})}function q0(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await _()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData(Ge(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function J(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function K0(e,t,r,n){let o=await _()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await J(o);return {status:o.status,data:s}}async function B0(e){let r=await _()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await J(r);return {status:r.status,data:n}}async function N0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await _()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await J(s);}async function M0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await _()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return J(s)}async function Q0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},u=await _()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(u)}async function H0(e,t,r){let n={code:e,username:t,token:r},o=await _()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}async function Qi(e,t){let r={code:e};t&&(r.id=t);let i=await _()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Hi(e,t){let r={code:e,url:t},i=await _()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}var Ju="https://i.ecency.com";async function Ui(e,t,r){let n=_(),i=new FormData;i.append("file",e);let o=await n(`${Ju}/hs/${t}`,{method:"POST",body:i,signal:r});return J(o)}async function U0(e,t,r,n){let i=_(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return J(s)}async function Vi(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function ji(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await _()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return J(a)}async function Li(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},u=await _()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(u)}async function $i(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function Wi(e,t,r,n,i,o,s,a){let u={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(u.options=o);let l=await _()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return J(l)}async function Gi(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function zi(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(i)}async function V0(e,t,r){let n={code:e,author:t,permlink:r},o=await _()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}async function j0(e,t,r){let n={username:e,email:t,friend:r},o=await _()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(o)}function z0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return ji(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(c.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function eO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:u})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Li(t,i,o,s,a,u)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function sO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return $i(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=c.posts.drafts(e),a=c.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let u=o.getQueryData(s);u&&o.setQueryData(s,u.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:u,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);n?.(i);}})}function lO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:u,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Wi(t,i,o,s,a,u,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function yO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return Gi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function vO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return zi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)}),o.invalidateQueries({queryKey:c.posts.drafts(e)});},onError:n})}function EO(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Hi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.images(e)});},onError:n})}function RO(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Vi(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],u=>u?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},u=>u&&{...u,pages:u.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function DO(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Ui(r,n,i),onSuccess:e,onError:t})}function Qt(e,t){return `/@${e}/${t}`}function sp(e,t,r){return (r??b()).getQueryData(c.posts.entry(Qt(e,t)))}function ap(e,t){(t??b()).setQueryData(c.posts.entry(Qt(e.author,e.permlink)),e);}function Mt(e,t,r,n){let i=n??b(),o=Qt(e,t),s=i.getQueryData(c.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(c.posts.entry(o),a),s}var ke;(a=>{function e(u,p,l,f,m){Mt(u,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(u,p,l,f){Mt(u,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(u,p,l,f){Mt(u,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(u,p,l,f){Mt(p,l,m=>({...m,children:m.children+1,replies:[u,...m.replies]}),f);}a.addReply=n;function i(u,p){u.forEach(l=>ap(l,p));}a.updateEntries=i;function o(u,p,l){(l??b()).invalidateQueries({queryKey:c.posts.entry(Qt(u,p))});}a.invalidateEntry=o;function s(u,p,l){return sp(u,p,l)}a.getEntry=s;})(ke||(ke={}));function cp(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function up(e,t,r){let n=ke.getEntry(t.author,t.permlink,r);if(!n?.active_votes||cp(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);ke.updateVotes(t.author,t.permlink,i,o,r);}function UO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[br(e,n,i,o)],async(n,i)=>{up(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function WO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[Ar(e,n,i,o??false)],async(n,i)=>{let o=ke.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));ke.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:c.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function YO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Me(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let u=[c.accounts.full(e),c.resourceCredits.account(e)];if(!o){u.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;u.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(u);}},t,"posting",{broadcastMode:r})}function ex(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function Ji(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[u,p]of a)p&&(s.set(u,p),o.setQueryData(u,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Yi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function tx(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(c.posts.entry(o));return s&&i.setQueryData(c.posts.entry(o),{...s,...r}),s}function rx(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(c.posts.entry(o),r);}function ax(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[vr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:Ji(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Yi(s);}})}function lx(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(Ne(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true}=n.options;i.push(Me(n.author,n.permlink,o,s,a,u,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function gx(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Me(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[c.resourceCredits.account(e)];s.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,u=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===u}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function wx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[$r(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.posts._promotedPrefix],[...c.points._prefix(e)],c.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var pp=[3e3,3e3,3e3],lp=e=>new Promise(t=>setTimeout(t,e));async function dp(e,t){return g("condenser_api.get_content",[e,t])}async function fp(e,t,r=0,n){let i=n?.delays??pp,o;try{o=await dp(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await lp(s),fp(e,t,r+1,n)}var Ye={};wt(Ye,{useRecordActivity:()=>zr});function gp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function zr(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=_(),i=gp(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function Cx(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function Ix(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function Nx(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Ht="threespeakfund",jx=1100;function wp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function Lx(e,t){if(!wp(t))return e;let r=e.find(n=>n.account===Ht);return r&&r.weight===1100?e:r?e.map(n=>n.account===Ht?{...n,weight:1100}:n):[...e,{account:Ht,weight:1100}]}function $x(e){return e===Ht}var Xr={};wt(Xr,{getAccountTokenQueryOptions:()=>Yr,getAccountVideosQueryOptions:()=>xp});var Jr={};wt(Jr,{getDecodeMemoQueryOptions:()=>Ap});function Ap(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Yn.Client({accessToken:r}).decode(t)}})}var Xi={queries:Jr};function Yr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await _()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=Xi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function xp(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Yr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await _()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var uE={queries:Xr};function gE(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await _()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function wE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await _()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function PE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function SE(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function FE(){return queryOptions({queryKey:c.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await g("rc_api.get_resource_params",{})})}var Zi=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var eo={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function KE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return eo;let{current_mana:i,max_mana:o}=Tt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...eo,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,u=s*a,p=iBigInt(typeof e=="string"?e:Math.trunc(e));function Ip(e,t,r,n){if(r<=0||n<=0)return 0;let i=Xe(e.coeff_a),o=Xe(e.coeff_b),s=Xe(e.shift),a=Xe(n)*i>>s;a+=1n,a*=Xe(r);let u=o+(t>0?Xe(t):0n);return u===0n?0:Number(a/u+1n)}function Dp({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:i=false},o){let s=o.resource_state_bytes,a=o.resource_execution_time;return {resource_history_bytes:e,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:s.comment_base_size+s.comment_permlink_char_size*t+s.transaction_base_size+s.comment_beneficiaries_member_size*n,resource_execution_time:a.comment_time+a.transaction_time+a.verify_authority_time*r+(i?a.comment_options_time:0)}}var he=e=>{let t=gr(e);return $e(t)+t},Kp=e=>1+he(e.parent_author)+he(e.parent_permlink)+he(e.author)+he(e.permlink)+he(e.title)+he(e.body)+he(e.json_metadata),Bp=(e,t)=>{let r=t.beneficiaries??[],n=1+he(e.author)+he(e.permlink)+qp+2+2;return n+=$e(r.length>0?1:0),r.length>0&&(n+=1+$e(r.length),r.forEach(i=>{n+=he(i.account)+2;})),n};function Np({op:e,options:t,signatures:r=1}){let n=[Kp(e)];return t&&n.push(Bp(e,t)),Rp+$e(n.length)+n.reduce((i,o)=>i+o,0)+$e(r)+Fp*r}var Mp={ready:false,cost:0,transactionBytes:0,breakdown:[]};function QE({op:e,options:t,rcParams:r,rcStats:n,signatures:i=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return Mp;let o=Np({op:e,options:t,signatures:i}),s=Dp({transactionBytes:o,permlinkLength:gr(e.permlink),signatures:i,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),u=0,p=[];return Zi.forEach((l,f)=>{let m=r.resource_params[l],y=Number(n.pool[f]??0),h=Number(n.share[f]??0);if(!m||h<=0)return;let x=s[l]*Number(m.resource_dynamics_params.resource_unit??1),E=Number(BigInt(a)*BigInt(h)/10000n),P=Ip(m.price_curve_params,y,x,E);u+=P,p.push({resource:l,usage:x,cost:P});}),{ready:true,cost:u,transactionBytes:o,breakdown:p}}function jE(e,t,r){return queryOptions({queryKey:["games","status-check",r,e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function zE(e,t,r,n){let{mutateAsync:i}=zr(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function ZE(e){let t=e?.replace("@","");return queryOptions({queryKey:c.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await _()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var Vp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function tS(e,t){return Vp.find(r=>r.tier===e&&r.id===t)}var jp=25;function Lp(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function rS(e){return Lp(e)>jp}var nS=300,iS=2;function Gp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function zp(e){let r=await _()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Gp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function cS(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return zp(t)},onSuccess(){n&&r.invalidateQueries({queryKey:c.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:c.quests.status(n)});}})}function dS(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Fr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function yS(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[qr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function bS(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[Br(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function OS(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[Ir(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>{if(!a)return a;let u=[...a.team??[]],p=u.findIndex(([l])=>l===o.account);return p>=0?u[p]=[u[p][0],o.role,u[p][2]??""]:u.push([o.account,o.role,""]),{...a,team:u}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)],c.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function kS(e,t,r,n){return v(["communities","update",e],t,i=>[Dr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function FS(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Wr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.communities.singlePrefix(i.name)],[...c.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function KS(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Kr(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.posts.entry(`/@${i.account}/${i.permlink}`),[...c.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function HS(e,t,r=100,n=void 0,i=true){return queryOptions({queryKey:c.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function $S(e,t){return queryOptions({queryKey:c.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function YS(e,t="",r=true){return queryOptions({queryKey:c.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>wi(e??"",t)})}var to=100;async function ro(e,t){return await g("bridge.list_subscribers",{community:e,limit:to,...t?{last:t}:{}})??[]}function nk(e){return queryOptions({queryKey:c.communities.subscribers(e),queryFn:async()=>ro(e,null),staleTime:6e4})}function ik(e){return infiniteQueryOptions({queryKey:c.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>ro(e,t),getNextPageParam:t=>t?.length>=to?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function pk(e,t){return infiniteQueryOptions({queryKey:c.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function mk(){return queryOptions({queryKey:c.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var nl=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(nl||{}),yk={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function _k(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function wk({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function Pk(e,t){return queryOptions({queryKey:c.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function Sk(e,t,r=void 0){return infiniteQueryOptions({queryKey:c.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var sl=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(sl||{});var al=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))(al||{}),no=[1,2,3,4,5,6,10,13,15,19,20,21,22],cl=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(cl||{});function Ik(e,t,r){return queryOptions({queryKey:c.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...no]})})}function Nk(){return queryOptions({queryKey:c.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function Uk(e){return queryOptions({queryKey:c.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function fl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function io(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function zk(e,t,r,n){let i=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!(!e||!t))return Qi(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:c.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:c.notifications._prefix,predicate:l=>{let f=l.state.data;return io(f)}});a.forEach(([l,f])=>{if(f&&io(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>fl(h,o)))};i.setQueryData(l,m);}});let u=c.notifications.unreadCount(e),p=i.getQueryData(u);return typeof p=="number"&&p>0&&(s.push([u,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(u,p-1):i.setQueryData(u,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(c.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([u,p])=>{i.setQueryData(u,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:c.notifications._prefix});}})}function Zk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Sr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function nC(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function fC(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),u=It(a);return s.map(l=>({...l,voterAccount:u.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function hC(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function vC(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[Rr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.proposals.list(),c.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function xC(e,t,r){return v(["proposals","create"],e,n=>[Tr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.proposals.list()]);},t,"active",{broadcastMode:r})}function CC(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthre("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function BC(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function HC(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function LC(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function zC(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function ZC(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function nT(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function cT(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function dT(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await _()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function yT(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function bT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function fe(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ue(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function Rl(e){if(!e||typeof e!="object")return;let t=e;return {name:fe(t.name)??"",symbol:fe(t.symbol)??"",layer:fe(t.layer)??"hive",balance:ue(t.balance)??0,fiatRate:ue(t.fiatRate)??0,currency:fe(t.currency)??"usd",precision:ue(t.precision)??3,address:fe(t.address),error:fe(t.error),pendingRewards:ue(t.pendingRewards),pendingRewardsFiat:ue(t.pendingRewardsFiat),liquid:ue(t.liquid),liquidFiat:ue(t.liquidFiat),savings:ue(t.savings),savingsFiat:ue(t.savingsFiat),staked:ue(t.staked),stakedFiat:ue(t.stakedFiat),iconUrl:fe(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ue(t.apr)}}function Fl(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function ql(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function oo(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${M.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=Fl(o).map(a=>Rl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:ql(o)??e,currency:fe(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Ut(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Pe()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Pe().queryKey),r=b().getQueryData(Q(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=T(r.balance).amount,s=T(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function so(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Pe()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Q(e).queryKey),r=b().getQueryData(Pe().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:T(t.hbd_balance).amount+T(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:T(t.hbd_balance).amount},{name:"savings",balance:T(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Bl(e){let u=9.5-(e.headBlock-7e6)/25e4*.01;u<.95&&(u=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*u*p/f).toFixed(3)}function ao(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Pe()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Pe().queryKey),r=b().getQueryData(Q(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=T(r.vesting_shares).amount,a=T(r.delegated_vesting_shares).amount,u=T(r.received_vesting_shares).amount,p=T(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=ni(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Le(s,t.hivePerMVests).toFixed(3),y=+Le(a,t.hivePerMVests).toFixed(3),h=+Le(u,t.hivePerMVests).toFixed(3),x=+Le(l,t.hivePerMVests).toFixed(3),E=+Le(f,t.hivePerMVests).toFixed(3),P=Math.max(m-x,0),O=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+P.toFixed(3),apr:Bl(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+O.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...x>0?[{name:"pending_power_down",balance:+x.toFixed(3)}]:[],...E>0&&E!==x?[{name:"next_power_down",balance:+E.toFixed(3)}]:[]]}}})}var B=ie.operations,Zr={transfers:[B.transfer,B.transfer_to_savings,B.transfer_from_savings,B.cancel_transfer_from_savings,B.recurrent_transfer,B.fill_recurrent_transfer,B.escrow_transfer,B.fill_recurrent_transfer],"market-orders":[B.fill_convert_request,B.fill_order,B.fill_collateralized_convert_request,B.limit_order_create2,B.limit_order_create,B.limit_order_cancel],interests:[B.interest],"stake-operations":[B.return_vesting_delegation,B.withdraw_vesting,B.transfer_to_vesting,B.set_withdraw_vesting_route,B.update_proposal_votes,B.fill_vesting_withdraw,B.account_witness_proxy,B.delegate_vesting_shares],rewards:[B.author_reward,B.curation_reward,B.producer_reward,B.claim_reward_balance,B.comment_benefactor_reward,B.liquidity_reward,B.proposal_pay],"":[]};var LT=Object.keys(ie.operations);var co=ie.operations,GT=co,zT=Object.entries(co).reduce((e,[t,r])=>(e[r]=t,e),{});var uo=ie.operations;function Ml(e){return Object.prototype.hasOwnProperty.call(uo,e)}function gt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in Zr){Zr[a].forEach(u=>o.add(u));return}Ml(a)&&o.add(uo[a]);});let s=Ul(Array.from(o));return {filterKey:i,filterArgs:s}}function en(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Ql(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Hl(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Ul(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,Hl(Number(s),t),...n])).map(u=>({num:u[0],type:u[1].op[0],timestamp:u[1].timestamp,trx_id:u[1].trx_id,...u[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return T(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return T(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return T(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=T(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return T(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function sR(e,t=20,r=[]){let{filterKey:n}=gt(r),i=en(r);return infiniteQueryOptions({...Vt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(u=>{switch(u.type){case "author_reward":case "comment_benefactor_reward":return T(u.hbd_payout).amount>0;case "claim_reward_balance":return T(u.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return T(u.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return T(u.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=T(u.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(u.type)}}))})})}function lR(e,t=20,r=[]){let{filterKey:n}=gt(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return infiniteQueryOptions({...Vt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return T(p.vesting_payout).amount>0;case "claim_reward_balance":return T(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(T(p.amount).symbol);case "fill_recurrent_transfer":let m=T(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function po(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function tn(e,t){return new Date(e.getTime()-t*1e3)}function gR(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,po(t),po(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[tn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[tn(n,Math.max(100*e,28800)),tn(n,e)]})}function wR(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function PR(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function kR(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>T(n.vesting_shares).amount-T(r.vesting_shares).amount)})}function FR(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function KR(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function QR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function jR(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function GR(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function lo(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function XR(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[lo(i),lo(n),e])})}function rF(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function sF(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function pF(e,t,r){return v(["market","limit-order-create"],e,n=>[Nt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function mF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Nr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function yt(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function hF(e,t,r,n){let i=_(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return yt(s)}async function fo(e){if(e==="hbd")return 1;let t=_(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await yt(n)).hive_dollar[e]}async function _F(e,t){let n=await _()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return yt(n)}async function wF(){let t=await _()(d.privateApiHost+"/private-api/market-data/latest");return yt(t)}async function bF(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return yt(t)}var nd={"Content-type":"application/json"};async function id(e){let t=_(),r=M.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:nd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ce(e,t){try{return await id(e)}catch{return t}}async function PF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([Ce({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ce({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((u,p)=>{let l=Number(u.price??0);return Number(p.price??0)-l}),s=a=>a.sort((u,p)=>{let l=Number(u.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function OF(e,t=50){return Ce({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function xF(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([Ce({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ce({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),u=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...u].sort((p,l)=>l.timestamp-p.timestamp)}async function od(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Ce({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Ze(e,t){return od(t,e)}async function jt(e){return Ce({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Lt(e){return Ce({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function mo(e,t,r,n){let i=_(),o=M.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function go(e,t="daily"){let r=_(),n=M.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function yo(e){let t=_(),r=M.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function $t(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>jt(e)})}function FF(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ze()})}function ho(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Lt(e)})}function MF(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return mo(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function VF(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>go(e,t)})}function WF(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await yo(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function _o(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ze(e,t)})}function et(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,u=typeof a=="string"?parseFloat(a):a;return s+=u.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var Wt=class{constructor(t){A(this,"symbol");A(this,"name");A(this,"icon");A(this,"precision");A(this,"stakingEnabled");A(this,"delegationEnabled");A(this,"balance");A(this,"stake");A(this,"stakedBalance");A(this,"delegationsIn");A(this,"delegationsOut");A(this,"usdValue");A(this,"hasDelegations",()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false);A(this,"delegations",()=>this.hasDelegations()?`(${et(this.stake,{fractionDigits:this.precision})} + ${et(this.delegationsIn,{fractionDigits:this.precision})} - ${et(this.delegationsOut,{fractionDigits:this.precision})})`:"");A(this,"staked",()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():et(this.stakedBalance,{fractionDigits:this.precision}):"-");A(this,"balanced",()=>this.balance<1e-4?this.balance.toString():et(this.balance,{fractionDigits:this.precision}));this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}};function oq(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await jt(e),i=await Lt(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),u=[...s,...a.length?await Ze(void 0,a):[]];return n.map(p=>{let l=i.find(E=>E.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=u.find(E=>E.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),x=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new Wt({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:x})})},enabled:!!e})}function wo(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Ut(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(ho([t])),s=await r.ensureQueryData($t(e)),a=await r.ensureQueryData(_o(void 0,t)),u=o?.find(E=>E.symbol===t),p=s?.find(E=>E.symbol===t),f=+(a?.find(E=>E.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),x=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&x.push({name:"unstaking",balance:h}),{name:t,title:u?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:x}}})}function ht(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function bo(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(ht(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(ht(e).queryKey)?.points??0)})})}function Pq(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:u,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:u??void 0,to:p??void 0,memo:l??void 0}))})}function Dq(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await fo(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=oo(e,i,true),u=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let E=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(E){let P=Math.abs(Number.parseFloat(E[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:P}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:P}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:P});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await u();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Ut(e));else if(t==="HP")l=await o(ao(e));else if(t==="HBD")l=await o(so(e));else if(t==="POINTS")l=await o(bo(e));else if((await n.ensureQueryData($t(e))).some(m=>m.symbol===t))l=await o(wo(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var wd=(P=>(P.Transfer="transfer",P.TransferToSavings="transfer-saving",P.WithdrawFromSavings="withdraw-saving",P.Delegate="delegate",P.PowerUp="power-up",P.PowerDown="power-down",P.WithdrawRoutes="withdraw-routes",P.ClaimInterest="claim-interest",P.Swap="swap",P.Convert="convert",P.Gift="gift",P.Promote="promote",P.Claim="claim",P.Buy="buy",P.Stake="stake",P.Unstake="unstake",P.Undelegate="undelegate",P))(wd||{});function Hq(e,t,r){return v(["wallet","transfer"],e,n=>[Qe(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function $q(e,t,r){return v(["wallet","transfer-point"],e,n=>[Je(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Yq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[dt(e,n.delegatee,n.vestingShares)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function rI(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[ft(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await k(t?.adapter,r,[c.wallet.withdrawRoutes(e),c.accounts.full(e),c.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function sI(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function lI(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[ze(e,n.to,n.amount,n.memo)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function yI(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[He(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function vI(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[pt(e,n.to,n.amount)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function EI(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[lt(e,n.vestingShares)],async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function RI(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Pr(e,n.amount,n.requestId):mt(e,n.amount,n.requestId)],async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function KI(e,t,r){return v(["wallet","claim-interest"],e,n=>ut(e,n.to,n.amount,n.memo,n.requestId),async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var bd=5e3,Gt=new Map;function HI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Mr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],c.assets.hiveGeneralInfo(e),c.assets.hbdGeneralInfo(e),c.assets.hivePowerGeneralInfo(e)],o=Gt.get(n);o&&(clearTimeout(o),Gt.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Gt.delete(n);}},bd);Gt.set(n,s);},t,"posting",{broadcastMode:r})}function LI(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function zI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function ZI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nD(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function aD(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function lD(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await k(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function vd(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Qe(n,i,o,s)];case "transfer-saving":return [ze(n,i,o,s)];case "withdraw-saving":return [He(n,i,o,s,a)];case "power-up":return [pt(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Qe(n,i,o,s)];case "transfer-saving":return [ze(n,i,o,s)];case "withdraw-saving":return [He(n,i,o,s,a)];case "claim-interest":return ut(n,i,o,s,a);case "convert":return [mt(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [lt(n,o)];case "delegate":return [dt(n,i,o)];case "withdraw-routes":return [ft(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Je(n,i,o,s)];break}return null}function Ad(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [Ue(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [Ue(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [Ue(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [Ue(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [Ue(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [Or(n,[e])]}return null}function Pd(e){return e==="claim"?"posting":"active"}function hD(e,t,r,n,i){let{mutateAsync:o}=Ye.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=vd(t,r,s);if(a)return a;let u=Ad(t,r,s);if(u)return u;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,Pd(r),{broadcastMode:i})}function vD(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[xr(e,n,i)],async(n,i)=>{await k(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),c.resourceCredits.account(e),c.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function xD(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[kr(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function CD(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Cr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function xd(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function DD(e){return infiniteQueryOptions({queryKey:c.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await re("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(xd),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function KD(e,t,r,n="vests",i="desc"){return queryOptions({queryKey:c.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await re("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function BD(e){return queryOptions({queryKey:c.witnesses.voterCount(e),queryFn:async()=>await re("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Ed=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(Ed||{});async function kd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await _()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function jD(e,t,r,n){let{mutateAsync:i}=Ye.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>kd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(ht(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var Ao=/(^|\s)author:([^\s]+)/g,Po=/(^|\s)type:([^\s]+)/g,Oo=/(^|\s)category:([^\s]+)/g,xo=/(^|\s)tag:([^\s]+)/g;var So=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(So||{}),$D=5,WD=100;function ko(e){return e.trim().split(/\s+/)[0]??""}function Cd(e){return ko(e).replace(/^@+/,"").toLowerCase()}function Td(e){return ko(e).replace(/^#+/,"").toLowerCase()}function Rd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function GD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=Cd(t),a=Td(n),u=Rd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),u.length>0&&p.push(`tag:${u.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:u}}var Eo=class{constructor(t){A(this,"query","");A(this,"search","");A(this,"author","");A(this,"type","");A(this,"category","");A(this,"tags",[]);A(this,"grab",t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""});A(this,"grabAuthor",()=>{this.author=this.grab(Ao);});A(this,"grabType",()=>{let t=this.grab(Po);Object.values(So).includes(t)&&(this.type=t);});A(this,"grabCategory",()=>{this.category=this.grab(Oo);});A(this,"grabTags",()=>{let t=new Set;this.tags=[...this.query.matchAll(xo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));});A(this,"grabSearch",()=>{for([Ao,Po,Oo,xo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();});this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}};async function Oe(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Te(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var qd=isServer?0:3;function _t(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let u=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:ve(Ae,s)});return Oe(u,Te)},retry:_t})}function sK(e,t,r=true){return infiniteQueryOptions({queryKey:c.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",u=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:u,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:ve(Ae,i)});return Oe(y,Te)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:_t})}async function pK(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await _()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:ve(Ae,s)});return Oe(p,Te)}async function Co(e,t,r=Ae){let i=await _()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:ve(r,t)});return Oe(i,Te)}async function lK(e,t){let n=await _()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:ve(Ae,t)}),i=await Oe(n,Array.isArray);return i?.length>0?i:[e]}var Bd=4368*60*60*1e3,Nd=4,Md=3e3,Qd=2e3,Hd=4e3,yK=2;function Ud(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Vd(e){let t=5381;for(let r=0;r>>0).toString(36)}function hK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Ud(e.body??"",Md),o=Vd(`${t}|${n.join(",")}|${i}`);return queryOptions({queryKey:c.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Bd).toISOString().slice(0,19),u=await Co({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?Qd:Hd),p=[],l=new Set;for(let f of u.results){if(p.length>=Nd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function PK(e,t=5){let r=e.trim();return queryOptions({queryKey:c.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Dt(n)},enabled:!!r})}function kK(e,t=10){let r=e.trim();return queryOptions({queryKey:c.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function IK(e,t,r,n,i,o){return infiniteQueryOptions({queryKey:c.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let u={q:e,sort:t,hide_low:r};n&&(u.since=n),s&&(u.scroll_id=s),i!==void 0&&(u.votes=i),o&&(u.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(u),signal:ve(Ae,a)});return Oe(p,Te)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:_t})}function NK(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function zd(e){let r=await _()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function UK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:c.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return zd(t)},enabled:!!r&&!!t})}async function Xd(e,t){let n=await _()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Zd(e,t,r){return e.setQueryData(c.support.settings(t),r),e.invalidateQueries({queryKey:c.support.settings(t)})}function WK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Xd(t,i)},onSuccess(i){n&&Zd(r,n,i);}})}function YK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function tB(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function oB(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function uB(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function fB(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function hB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[jr(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function vB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Lr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function OB(e){let r=await _()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var af="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function kB(){return queryOptions({queryKey:c.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(af,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` +`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var TB=1.1,cf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(cf||{});function RB(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function lf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let u=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:u?{total_votes:u.total_votes??0,hive_hp:u.hive_hp,hive_proxied_hp:u.hive_proxied_hp,hive_hp_incl_proxied:u.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function KB(e,t){return queryOptions({queryKey:c.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?Zn:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return lf(o[0])}})}function MB(e,t,r){return v(c.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** * @license bytebuffer.ts (c) 2015 Daniel Wirtz * Backing buffer: ArrayBuffer, Accessor: DataView * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bytebuffer.ts for details * modified by @xmcl/bytebuffer * And customized for hive-tx - */export{ai as ACCOUNT_OPERATION_GROUPS,Sa as ALL_ACCOUNT_OPERATIONS,Xi as ALL_NOTIFY_TYPES,id as AssetOperation,Dm as BROADCAST_INCLUSION_DELAY_MS,Ci as BuySellTransactionType,d as CONFIG,N as ConfigManager,ze as EcencyAnalytics,Jn as EcencyQueriesManager,Se as EntriesCacheManagement,$n as ErrorType,zr as HIVE_ACCOUNT_OPERATION_GROUPS,_T as HIVE_OPERATION_LIST,PT as HIVE_OPERATION_NAME_BY_ID,AT as HIVE_OPERATION_ORDERS,jt as HiveEngineToken,Gi as HiveSignerIntegration,qe as HiveTxTransaction,ve as INTERNAL_API_TIMEOUT_MS,vD as MAX_SEARCH_QUERY_LENGTH,bD as MAX_SEARCH_TAGS,Un as Memo,Ct as NaiMap,Lp as NotificationFilter,Wp as NotificationViewType,$p as NotifyTypes,qc as OPERATION_AUTHORITY_MAP,Ti as OrderIdPrefix,iB as POLLS_PROTOCOL_VERSION,ld as PointTransactionType,$d as PollPreferredInterpretation,U as PrivateKey,X as PublicKey,kp as QUEST_CATALOG,Cp as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,Up as ROLES,zn as SERVER_GC_TIME_MS,jD as SIMILAR_ENTRIES_MIN_RENDER,FE as STREAK_FREEZE_MAX_OWNED,RE as STREAK_FREEZE_PRICE,Ji as SUBSCRIBERS_PAGE_SIZE,vo as SearchQuery,Ao as SearchType,Oe as Signature,wi as SortOrder,Yn as Symbol,Mt as THREESPEAK_BENEFICIARY_ACCOUNT,kx as THREESPEAK_BENEFICIARY_WEIGHT,Wx as ThreeSpeakIntegration,oa as accountNameByteLength,Qi as addDraft,Bi as addImage,MO as addOptimisticDiscussionEntry,Vi as addSchedule,Md as applySupportSettingsUpdate,ip as applyVoteCacheUpdate,ue as bridgeApiCall,Gn as broadcastJson,te as broadcastOperations,jn as broadcastOperationsAsync,Kr as buildAccountCreateOp,tc as buildAccountUpdate2Op,ec as buildAccountUpdateOp,ac as buildActiveCustomJsonOp,Qr as buildBoostPlusOp,ki as buildCancelTransferFromSavingsOp,nc as buildChangeRecoveryAccountOp,Mr as buildClaimAccountOp,st as buildClaimInterestOps,Dr as buildClaimRewardBalanceOp,_r as buildCollateralizedConvertOp,Be as buildCommentOp,Me as buildCommentOptionsOp,Vr as buildCommunityRegistrationOp,lt as buildConvertOp,Br as buildCreateClaimedAccountOp,vr as buildDelegateRcOp,ct as buildDelegateVestingSharesOp,hr as buildDeleteCommentOp,br as buildEngineClaimOp,He as buildEngineOp,Xu as buildFlagPostOp,Ar as buildFollowOp,Nr as buildGrantPostingPermissionOp,Wu as buildIgnoreOp,Ir as buildLimitOrderCancelOp,Dt as buildLimitOrderCreateOp,Zu as buildLimitOrderCreateOpWithType,sc as buildMultiPointTransferOps,Lu as buildMultiTransferOps,qr as buildMutePostOp,Yu as buildMuteUserOp,Fr as buildPinPostOp,Ge as buildPointTransferOp,uc as buildPostingCustomJsonOp,ii as buildPostingJsonMetadata,fr as buildProfileMetadata,Ur as buildPromoteOp,Er as buildProposalCreateOp,Sr as buildProposalVoteOp,Hr as buildRcDelegationOp,wr as buildReblogOp,oc as buildRecoverAccountOp,$u as buildRecurrentTransferOp,zu as buildRemoveProposalOp,ic as buildRequestAccountRecoveryOp,Fi as buildRevokeKeysOp,rc as buildRevokePostingPermissionOp,AD as buildSearchQuery,Pr as buildSetLastReadOps,Tr as buildSetRoleOp,pt as buildSetWithdrawVestingRouteOp,kr as buildSubscribeOp,Qe as buildTransferFromSavingsOp,Ne as buildTransferOp,We as buildTransferToSavingsOp,at as buildTransferToVestingOp,qt as buildUnfollowOp,Gu as buildUnignoreOp,Cr as buildUnsubscribeOp,Rr as buildUpdateCommunityOp,Ju as buildUpdateProposalOp,yr as buildVoteOp,ut as buildWithdrawVestingOp,xr as buildWitnessProxyOp,Or as buildWitnessVoteOp,Ip as buyStreakFreezeRequest,St as calculateRCMana,pr as calculateVPMana,re as callREST,g as callRPC,Ue as callRPCBroadcast,xt as callWithQuorum,sP as canRevokeFromAuthority,nh as checkFavoriteQueryOptions,Iy as checkUsernameWalletsPendingQueryOptions,fd as claimPointsRequest,Jr as collectRequestedOperations,Jm as decodeObj,gc as dedupeAndSortKeyAuths,Ui as deleteDraft,Ni as deleteImage,ji as deleteSchedule,TP as downVotingPower,TE as earnsQuestContentCredit,zm as encodeObj,Cx as enforceThreeSpeakBeneficiary,mE as estimateRcPrecheck,ri as extractAccountProfile,ks as formatError,Ye as formattedNumber,aC as getAccountDelegationsQueryOptions,Q as getAccountFullQueryOptions,MS as getAccountNotificationsInfiniteQueryOptions,dh as getAccountPendingRecoveryQueryOptions,mr as getAccountPosts,w_ as getAccountPostsInfiniteQueryOptions,__ as getAccountPostsQueryOptions,lE as getAccountRcQueryOptions,ah as getAccountRecoveriesQueryOptions,wh as getAccountReputationsQueryOptions,Vy as getAccountSubscriptionsQueryOptions,gv as getAccountVoteHistoryInfiniteQueryOptions,cq as getAccountWalletAssetInfoQueryOptions,Zg as getAccountsQueryOptions,Rv as getAggregatedBalanceQueryOptions,vg as getAiAssistPriceQueryOptions,hg as getAiGeneratePriceQueryOptions,xg as getAiTranscribePriceQueryOptions,fo as getAllHiveEngineTokensQueryOptions,dk as getAnnouncementsQueryOptions,rB as getBadActorsQueryOptions,Ev as getBalanceHistoryInfiniteQueryOptions,Gy as getBookmarksInfiniteQueryOptions,Wy as getBookmarksQueryOptions,HK as getBoostPlusAccountPricesQueryOptions,xK as getBoostPlusPricesQueryOptions,Th as getBotsQueryOptions,w as getBoundFetch,JP as getChainPropertiesQueryOptions,_C as getCollateralizedConversionRequestsQueryOptions,ib as getCommentHistoryQueryOptions,t_ as getCommunities,gS as getCommunitiesQueryOptions,gi as getCommunity,bS as getCommunityContextQueryOptions,WS as getCommunityPermissions,xS as getCommunityQueryOptions,FS as getCommunitySubscribersInfiniteQueryOptions,RS as getCommunitySubscribersQueryOptions,$S as getCommunityType,Cw as getContentQueryOptions,Iw as getContentRepliesQueryOptions,ID as getControversialRisingInfiniteQueryOptions,gC as getConversionRequestsQueryOptions,ao as getCurrencyRate,WR as getCurrencyRates,$R as getCurrencyTokenRate,IR as getCurrentMedianHistoryPriceQueryOptions,Ic as getCustomJsonAuthority,ub as getDeletedEntryQueryOptions,wx as getDiscoverCurationQueryOptions,fx as getDiscoverLeaderboardQueryOptions,mi as getDiscussion,l_ as getDiscussionQueryOptions,_i as getDiscussionsQueryOptions,G_ as getDraftsInfiniteQueryOptions,W_ as getDraftsQueryOptions,Ae as getDynamicPropsQueryOptions,_w as getEntryActiveVotesQueryOptions,Zy as getFavoritesInfiniteQueryOptions,Xy as getFavoritesQueryOptions,TR as getFeedHistoryQueryOptions,iy as getFollowCountQueryOptions,cy as getFollowersQueryOptions,my as getFollowingQueryOptions,pw as getFragmentsInfiniteQueryOptions,$e as getFragmentsQueryOptions,jh as getFriendsInfiniteQueryOptions,Z_ as getGalleryImagesQueryOptions,wE as getGameStatusCheckQueryOptions,to as getHbdAssetGeneralInfoQueryOptions,IT as getHbdAssetTransactionsQueryOptions,Nt as getHiveAssetGeneralInfoQueryOptions,VT as getHiveAssetMetricQueryOptions,Qt as getHiveAssetTransactionsQueryOptions,WT as getHiveAssetWithdrawalRoutesQueryOptions,qF as getHiveEngineBalancesWithUsdQueryOptions,jl as getHiveEngineMetrics,ZR as getHiveEngineOpenOrders,YR as getHiveEngineOrderBook,mo as getHiveEngineTokenGeneralInfoQueryOptions,co as getHiveEngineTokenMetrics,uo as getHiveEngineTokenTransactions,fF as getHiveEngineTokenTransactionsQueryOptions,Ht as getHiveEngineTokensBalances,Vt as getHiveEngineTokensBalancesQueryOptions,Je as getHiveEngineTokensMarket,sF as getHiveEngineTokensMarketQueryOptions,Ut as getHiveEngineTokensMetadata,lo as getHiveEngineTokensMetadataQueryOptions,hF as getHiveEngineTokensMetricsQueryOptions,XR as getHiveEngineTradeHistory,po as getHiveEngineUnclaimedRewards,vF as getHiveEngineUnclaimedRewardsQueryOptions,wR as getHiveHbdStatsQueryOptions,Zx as getHivePoshLinksQueryOptions,ro as getHivePowerAssetGeneralInfoQueryOptions,NT as getHivePowerAssetTransactionsQueryOptions,YT as getHivePowerDelegatesInfiniteQueryOptions,rR as getHivePowerDelegatingsQueryOptions,GR as getHivePrice,eb as getImagesInfiniteQueryOptions,X_ as getImagesQueryOptions,QC as getIncomingRcQueryOptions,LR as getMarketData,AR as getMarketDataQueryOptions,mR as getMarketHistoryQueryOptions,pR as getMarketStatisticsQueryOptions,_y as getMutedUsersQueryOptions,xl as getNextAccountHistoryPageParam,av as getNormalizePostQueryOptions,x0 as getNotificationSetting,P0 as getNotifications,tk as getNotificationsInfiniteQueryOptions,uk as getNotificationsSettingsQueryOptions,YS as getNotificationsUnreadCountQueryOptions,RC as getOpenOrdersQueryOptions,Kc as getOperationAuthority,sR as getOrderBookQueryOptions,KC as getOutgoingRcDelegationsInfiniteQueryOptions,Ax as getPageStatsQueryOptions,go as getPointsAssetGeneralInfoQueryOptions,YF as getPointsAssetTransactionsQueryOptions,mt as getPointsQueryOptions,pB as getPollQueryOptions,eo as getPortfolioQueryOptions,Ja as getPost,e_ as getPostHeader,Nw as getPostHeaderQueryOptions,pi as getPostQueryOptions,db as getPostTipsQueryOptions,fi as getPostsRanked,S_ as getPostsRankedInfiniteQueryOptions,k_ as getPostsRankedQueryOptions,Dv as getProMembersQueryOptions,Ft as getProfiles,bv as getProfilesQueryOptions,BK as getPromotePriceQueryOptions,S0 as getPromotedPost,mw as getPromotedPostsQuery,Dc as getProposalAuthority,Rk as getProposalQueryOptions,Hk as getProposalVotesInfiniteQueryOptions,Dk as getProposalsQueryOptions,b as getQueryClient,CE as getQuestCatalogEntry,SE as getQuestsQueryOptions,qK as getRcDelegationActiveQueryOptions,CK as getRcDelegationPricesQueryOptions,aE as getRcStatsQueryOptions,M_ as getRebloggedByQueryOptions,q_ as getReblogsQueryOptions,jC as getReceivedVestingSharesQueryOptions,GC as getRecurrentTransfersQueryOptions,Ih as getReferralsInfiniteQueryOptions,Mh as getReferralsStatsQueryOptions,i_ as getRelationshipBetweenAccounts,si as getRelationshipBetweenAccountsQueryOptions,IP as getRequiredAuthority,dg as getRewardFundQueryOptions,US as getRewardedCommunitiesQueryOptions,PC as getSavingsWithdrawFromQueryOptions,V_ as getSchedulesInfiniteQueryOptions,U_ as getSchedulesQueryOptions,YD as getSearchAccountQueryOptions,Ty as getSearchAccountsByUsernameQueryOptions,uK as getSearchApiInfiniteQueryOptions,zh as getSearchFriendsQueryOptions,dK as getSearchPathQueryOptions,rK as getSearchTopicsQueryOptions,Eb as getShortsFeedQueryOptions,LD as getSimilarEntriesQueryOptions,yk as getSpotlightsQueryOptions,nE as getStatsQueryOptions,n_ as getSubscribers,r_ as getSubscriptions,yK as getSupportSettingsQueryOptions,Id as getSupportSettingsRequest,ER as getTradeHistoryQueryOptions,Eh as getTransactionsInfiniteQueryOptions,ew as getTrendingTagsQueryOptions,sw as getTrendingTagsWithStatsQueryOptions,Ow as getUserPostVoteQueryOptions,Lk as getUserProposalVotesQueryOptions,lC as getVestingDelegationExpirationsQueryOptions,nC as getVestingDelegationsQueryOptions,Pi as getVisibleFirstLevelThreadItems,Xb as getWavesByAccountQueryOptions,qb as getWavesByHostQueryOptions,Mb as getWavesByTagQueryOptions,bb as getWavesFeedQueryOptions,Vb as getWavesFollowingQueryOptions,vb as getWavesLatestFeedQueryOptions,rv as getWavesTrendingAuthorsQueryOptions,Wb as getWavesTrendingTagsQueryOptions,SC as getWithdrawRoutesQueryOptions,lD as getWitnessVoterCountQueryOptions,pD as getWitnessVotersPageQueryOptions,cD as getWitnessesInfiniteQueryOptions,mp as hasThreeSpeakEmbed,E as hiveTxConfig,ie as hiveTxUtils,XK as hsTokenRenew,k as invalidateAfterBroadcast,Xn as isCommunity,Zn as isEmptyDate,Ts as isInfoError,Rs as isNetworkError,Le as isQueryableAccountName,Cs as isResourceCreditsError,Tx as isThreeSpeakBeneficiary,np as isVoteAlreadyReflected,Vn as isWif,Us as isWrappedResponse,xy as lookupAccountsQueryOptions,Wm as makeQueryClient,oB as mapMetaChoicesToPollChoices,Oi as mapThreadItemsToWaveEntries,Ki as markNotifications,Tp as measureQuestContentLength,Li as moveSchedule,yi as normalizePost,md as normalizeSearchAuthor,gd as normalizeSearchCategory,yd as normalizeSearchTags,ae as normalizeToWrappedResponse,ye as normalizeWaveEntryFromApi,k0 as onboardEmail,Rt as parseAccounts,T as parseAsset,Ve as parseChainError,ia as parsePostingMetadataRoot,Ke as parseProfileMetadata,ni as pickRicherMetadataSnapshot,CP as powerRechargeTime,Kv as proMembersSet,RP as rcPower,$i as removeOptimisticDiscussionEntry,El as resolveAccountHistoryLimit,dt as resolveHiveOperationFilters,li as resolvePost,Wi as restoreDiscussionSnapshots,QO as restoreEntryInCache,jS as roleMap,O0 as saveNotificationSetting,MD as search,ND as searchPath,qD as searchQueryOptions,_m as sha256,we as shouldTriggerAuthFallback,b0 as signUp,Oo as similar,Ya as sortDiscussions,v0 as subscribeEmail,hu as toEntryArray,Hi as updateDraft,NO as updateEntryInCache,Bd as updateSupportSettingsRequest,Mi as uploadImage,E0 as uploadImageWithSignature,TA as useAccountFavoriteAdd,DA as useAccountFavoriteDelete,Wv as useAccountRelationsUpdate,dP as useAccountRevokeKey,YA as useAccountRevokePosting,Uv as useAccountUpdate,Ri as useAccountUpdateKeyAuths,LA as useAccountUpdatePassword,iP as useAccountUpdateRecovery,q0 as useAddDraft,i0 as useAddFragment,pO as useAddImage,z0 as useAddSchedule,qg as useAiAssist,Bg as useAiTranscribe,AA as useBookmarkAdd,EA as useBookmarkDelete,LK as useBoostPlus,v as useBroadcastMutation,KE as useBuyStreakFreeze,yP as useClaimAccount,DI as useClaimEngineRewards,pI as useClaimInterest,wD as useClaimPoints,gI as useClaimRewards,DO as useComment,oI as useConvert,OP as useCreateAccount,zO as useCrossPost,_I as useDelegateEngineToken,zI as useDelegateRc,xq as useDelegateVestingShares,LO as useDeleteComment,j0 as useDeleteDraft,gO as useDeleteImage,eO as useDeleteSchedule,l0 as useEditFragment,NI as useEngineMarketOrder,mA as useFollow,PE as useGameClaim,Cg as useGenerateImage,bP as useGrantPostingPermission,UR as useLimitOrderCancel,MR as useLimitOrderCreate,Pk as useMarkNotificationsRead,oO as useMoveSchedule,GE as useMutePost,pS as usePinPost,fB as usePollVote,nx as usePromote,Zk as useProposalCreate,zk as useProposalVote,zK as useRcDelegation,RO as useReblog,Lr as useRecordActivity,sS as useRegisterCommunityRewards,h0 as useRemoveFragment,XE as useSetCommunityRole,Sk as useSetLastRead,Tq as useSetWithdrawVestingRoute,$P as useSignOperationByHivesigner,NP as useSignOperationByKey,UP as useSignOperationByKeychain,SI as useStakeEngineToken,QE as useSubscribeCommunity,gq as useTransfer,Iq as useTransferEngineToken,jq as useTransferFromSavings,bq as useTransferPoint,Nq as useTransferToSavings,zq as useTransferToVesting,PI as useUndelegateEngineToken,wA as useUnfollow,RI as useUnstakeEngineToken,jE as useUnsubscribeCommunity,rS as useUpdateCommunity,M0 as useUpdateDraft,ZO as useUpdateReply,vK as useUpdateSupportSettings,_O as useUploadImage,EO as useVote,LI as useWalletOperation,eI as useWithdrawVesting,nD as useWitnessProxy,ZI as useWitnessVote,A0 as usrActivity,up as validatePostCreating,ci as verifyPostOnAlternateNode,je as vestsToHp,kP as votingPower,Fc as votingRshares,FP as votingValue,be as withTimeoutSignal};//# sourceMappingURL=index.js.map + */export{li as ACCOUNT_OPERATION_GROUPS,Fa as ALL_ACCOUNT_OPERATIONS,no as ALL_NOTIFY_TYPES,wd as AssetOperation,Jm as BROADCAST_INCLUSION_DELAY_MS,qi as BuySellTransactionType,d as CONFIG,M as ConfigManager,Ye as EcencyAnalytics,ei as EcencyQueriesManager,ke as EntriesCacheManagement,Jn as ErrorType,Zr as HIVE_ACCOUNT_OPERATION_GROUPS,LT as HIVE_OPERATION_LIST,zT as HIVE_OPERATION_NAME_BY_ID,GT as HIVE_OPERATION_ORDERS,Wt as HiveEngineToken,Xi as HiveSignerIntegration,Ie as HiveTxTransaction,Ae as INTERNAL_API_TIMEOUT_MS,WD as MAX_SEARCH_QUERY_LENGTH,$D as MAX_SEARCH_TAGS,$n as Memo,Ft as NaiMap,sl as NotificationFilter,cl as NotificationViewType,al as NotifyTypes,Nu as OPERATION_AUTHORITY_MAP,Ii as OrderIdPrefix,TB as POLLS_PROTOCOL_VERSION,Ed as PointTransactionType,cf as PollPreferredInterpretation,U as PrivateKey,X as PublicKey,Vp as QUEST_CATALOG,jp as QUEST_MIN_CONTENT_LENGTH,c as QueryKeys,Zi as RC_RESOURCE_NAMES,nl as ROLES,Zn as SERVER_GC_TIME_MS,yK as SIMILAR_ENTRIES_MIN_RENDER,iS as STREAK_FREEZE_MAX_OWNED,nS as STREAK_FREEZE_PRICE,to as SUBSCRIBERS_PAGE_SIZE,Eo as SearchQuery,So as SearchType,xe as Signature,Ai as SortOrder,ti as Symbol,Ht as THREESPEAK_BENEFICIARY_ACCOUNT,jx as THREESPEAK_BENEFICIARY_WEIGHT,uE as ThreeSpeakIntegration,pa as accountNameByteLength,ji as addDraft,Hi as addImage,ex as addOptimisticDiscussionEntry,Wi as addSchedule,Zd as applySupportSettingsUpdate,up as applyVoteCacheUpdate,ce as bridgeApiCall,Xn as broadcastJson,te as broadcastOperations,Gn as broadcastOperationsAsync,Qr as buildAccountCreateOp,su as buildAccountUpdate2Op,ou as buildAccountUpdateOp,du as buildActiveCustomJsonOp,jr as buildBoostPlusOp,Fi as buildCancelTransferFromSavingsOp,cu as buildChangeRecoveryAccountOp,Ur as buildClaimAccountOp,ut as buildClaimInterestOps,Mr as buildClaimRewardBalanceOp,Pr as buildCollateralizedConvertOp,Ne as buildCommentOp,Me as buildCommentOptionsOp,Wr as buildCommunityRegistrationOp,mt as buildConvertOp,Hr as buildCreateClaimedAccountOp,xr as buildDelegateRcOp,dt as buildDelegateVestingSharesOp,vr as buildDeleteCommentOp,Or as buildEngineClaimOp,Ue as buildEngineOp,nu as buildFlagPostOp,Er as buildFollowOp,Vr as buildGrantPostingPermissionOp,Xc as buildIgnoreOp,Nr as buildLimitOrderCancelOp,Nt as buildLimitOrderCreateOp,iu as buildLimitOrderCreateOpWithType,lu as buildMultiPointTransferOps,Jc as buildMultiTransferOps,Br as buildMutePostOp,ru as buildMuteUserOp,Kr as buildPinPostOp,Je as buildPointTransferOp,fu as buildPostingCustomJsonOp,ci as buildPostingJsonMetadata,hr as buildProfileMetadata,$r as buildPromoteOp,Tr as buildProposalCreateOp,Rr as buildProposalVoteOp,Lr as buildRcDelegationOp,Ar as buildReblogOp,pu as buildRecoverAccountOp,Yc as buildRecurrentTransferOp,eu as buildRemoveProposalOp,uu as buildRequestAccountRecoveryOp,Ki as buildRevokeKeysOp,au as buildRevokePostingPermissionOp,GD as buildSearchQuery,Sr as buildSetLastReadOps,Ir as buildSetRoleOp,ft as buildSetWithdrawVestingRouteOp,Fr as buildSubscribeOp,He as buildTransferFromSavingsOp,Qe as buildTransferOp,ze as buildTransferToSavingsOp,pt as buildTransferToVestingOp,Kt as buildUnfollowOp,Zc as buildUnignoreOp,qr as buildUnsubscribeOp,Dr as buildUpdateCommunityOp,tu as buildUpdateProposalOp,br as buildVoteOp,lt as buildWithdrawVestingOp,Cr as buildWitnessProxyOp,kr as buildWitnessVoteOp,zp as buyStreakFreezeRequest,Tt as calculateRCMana,fr as calculateVPMana,re as callREST,g as callRPC,Ve as callRPCBroadcast,kt as callWithQuorum,AP as canRevokeFromAuthority,wh as checkFavoriteQueryOptions,Jy as checkUsernameWalletsPendingQueryOptions,kd as claimPointsRequest,en as collectRequestedOperations,Ip as computeResourceCost,Dp as countCommentResourceUsage,lg as decodeObj,bu as dedupeAndSortKeyAuths,$i as deleteDraft,Vi as deleteImage,Gi as deleteSchedule,$P as downVotingPower,rS as earnsQuestContentCredit,pg as encodeObj,Lx as enforceThreeSpeakBeneficiary,QE as estimateCommentRcCost,Np as estimateCommentTransactionBytes,KE as estimateRcPrecheck,si as extractAccountProfile,qs as formatError,et as formattedNumber,qC as getAccountDelegationsQueryOptions,Q as getAccountFullQueryOptions,pk as getAccountNotificationsInfiniteQueryOptions,kh as getAccountPendingRecoveryQueryOptions,_r as getAccountPosts,Iw as getAccountPostsInfiniteQueryOptions,Dw as getAccountPostsQueryOptions,SE as getAccountRcQueryOptions,Ph as getAccountRecoveriesQueryOptions,Ih as getAccountReputationsQueryOptions,oh as getAccountSubscriptionsQueryOptions,Rv as getAccountVoteHistoryInfiniteQueryOptions,Dq as getAccountWalletAssetInfoQueryOptions,gy as getAccountsQueryOptions,Wv as getAggregatedBalanceQueryOptions,Bg as getAiAssistPriceQueryOptions,qg as getAiGeneratePriceQueryOptions,Hg as getAiTranscribePriceQueryOptions,_o as getAllHiveEngineTokensQueryOptions,Nk as getAnnouncementsQueryOptions,kB as getBadActorsQueryOptions,Uv as getBalanceHistoryInfiniteQueryOptions,ph as getBookmarksInfiniteQueryOptions,uh as getBookmarksQueryOptions,fB as getBoostPlusAccountPricesQueryOptions,YK as getBoostPlusPricesQueryOptions,$h as getBotsQueryOptions,_ as getBoundFetch,d0 as getChainPropertiesQueryOptions,LC as getCollateralizedConversionRequestsQueryOptions,bb as getCommentHistoryQueryOptions,hw as getCommunities,HS as getCommunitiesQueryOptions,wi as getCommunity,$S as getCommunityContextQueryOptions,wk as getCommunityPermissions,YS as getCommunityQueryOptions,ik as getCommunitySubscribersInfiniteQueryOptions,nk as getCommunitySubscribersQueryOptions,_k as getCommunityType,L_ as getContentQueryOptions,J_ as getContentRepliesQueryOptions,sK as getControversialRisingInfiniteQueryOptions,HC as getConversionRequestsQueryOptions,fo as getCurrencyRate,wF as getCurrencyRates,_F as getCurrencyTokenRate,sF as getCurrentMedianHistoryPriceQueryOptions,Mu as getCustomJsonAuthority,Ob as getDeletedEntryQueryOptions,Ix as getDiscoverCurationQueryOptions,Cx as getDiscoverLeaderboardQueryOptions,_i as getDiscussion,Sw as getDiscussionQueryOptions,Pi as getDiscussionsQueryOptions,pb as getDraftsInfiniteQueryOptions,ub as getDraftsQueryOptions,Pe as getDynamicPropsQueryOptions,D_ as getEntryActiveVotesQueryOptions,gh as getFavoritesInfiniteQueryOptions,mh as getFavoritesQueryOptions,rF as getFeedHistoryQueryOptions,by as getFollowCountQueryOptions,xy as getFollowersQueryOptions,Ty as getFollowingQueryOptions,E_ as getFragmentsInfiniteQueryOptions,Ge as getFragmentsQueryOptions,s_ as getFriendsInfiniteQueryOptions,gb as getGalleryImagesQueryOptions,jE as getGameStatusCheckQueryOptions,so as getHbdAssetGeneralInfoQueryOptions,sR as getHbdAssetTransactionsQueryOptions,Ut as getHiveAssetGeneralInfoQueryOptions,gR as getHiveAssetMetricQueryOptions,Vt as getHiveAssetTransactionsQueryOptions,wR as getHiveAssetWithdrawalRoutesQueryOptions,oq as getHiveEngineBalancesWithUsdQueryOptions,od as getHiveEngineMetrics,xF as getHiveEngineOpenOrders,PF as getHiveEngineOrderBook,wo as getHiveEngineTokenGeneralInfoQueryOptions,go as getHiveEngineTokenMetrics,mo as getHiveEngineTokenTransactions,MF as getHiveEngineTokenTransactionsQueryOptions,jt as getHiveEngineTokensBalances,$t as getHiveEngineTokensBalancesQueryOptions,Ze as getHiveEngineTokensMarket,FF as getHiveEngineTokensMarketQueryOptions,Lt as getHiveEngineTokensMetadata,ho as getHiveEngineTokensMetadataQueryOptions,VF as getHiveEngineTokensMetricsQueryOptions,OF as getHiveEngineTradeHistory,yo as getHiveEngineUnclaimedRewards,WF as getHiveEngineUnclaimedRewardsQueryOptions,jR as getHiveHbdStatsQueryOptions,gE as getHivePoshLinksQueryOptions,ao as getHivePowerAssetGeneralInfoQueryOptions,lR as getHivePowerAssetTransactionsQueryOptions,PR as getHivePowerDelegatesInfiniteQueryOptions,kR as getHivePowerDelegatingsQueryOptions,bF as getHivePrice,yb as getImagesInfiniteQueryOptions,mb as getImagesQueryOptions,dT as getIncomingRcQueryOptions,hF as getMarketData,GR as getMarketDataQueryOptions,QR as getMarketHistoryQueryOptions,KR as getMarketStatisticsQueryOptions,Dy as getMutedUsersQueryOptions,Ql as getNextAccountHistoryPageParam,Pv as getNormalizePostQueryOptions,H0 as getNotificationSetting,M0 as getNotifications,Sk as getNotificationsInfiniteQueryOptions,Ik as getNotificationsSettingsQueryOptions,Pk as getNotificationsUnreadCountQueryOptions,nT as getOpenOrdersQueryOptions,Hu as getOperationAuthority,FR as getOrderBookQueryOptions,cT as getOutgoingRcDelegationsInfiniteQueryOptions,Nx as getPageStatsQueryOptions,bo as getPointsAssetGeneralInfoQueryOptions,Pq as getPointsAssetTransactionsQueryOptions,ht as getPointsQueryOptions,KB as getPollQueryOptions,oo as getPortfolioQueryOptions,tc as getPost,yw as getPostHeader,tw as getPostHeaderQueryOptions,mi as getPostQueryOptions,kb as getPostTipsQueryOptions,hi as getPostsRanked,Vw as getPostsRankedInfiniteQueryOptions,jw as getPostsRankedQueryOptions,Yv as getProMembersQueryOptions,Dt as getProfiles,Kv as getProfilesQueryOptions,uB as getPromotePriceQueryOptions,V0 as getPromotedPost,T_ as getPromotedPostsQuery,Qu as getProposalAuthority,nC as getProposalQueryOptions,fC as getProposalVotesInfiniteQueryOptions,aC as getProposalsQueryOptions,b as getQueryClient,tS as getQuestCatalogEntry,ZE as getQuestsQueryOptions,oB as getRcDelegationActiveQueryOptions,tB as getRcDelegationPricesQueryOptions,FE as getRcResourceParamsQueryOptions,PE as getRcStatsQueryOptions,eb as getRebloggedByQueryOptions,zw as getReblogsQueryOptions,yT as getReceivedVestingSharesQueryOptions,bT as getRecurrentTransfersQueryOptions,Jh as getReferralsInfiniteQueryOptions,e_ as getReferralsStatsQueryOptions,bw as getRelationshipBetweenAccounts,pi as getRelationshipBetweenAccountsQueryOptions,JP as getRequiredAuthority,Sg as getRewardFundQueryOptions,mk as getRewardedCommunitiesQueryOptions,zC as getSavingsWithdrawFromQueryOptions,ob as getSchedulesInfiniteQueryOptions,ib as getSchedulesQueryOptions,PK as getSearchAccountQueryOptions,$y as getSearchAccountsByUsernameQueryOptions,IK as getSearchApiInfiniteQueryOptions,l_ as getSearchFriendsQueryOptions,NK as getSearchPathQueryOptions,kK as getSearchTopicsQueryOptions,Ub as getShortsFeedQueryOptions,hK as getSimilarEntriesQueryOptions,Uk as getSpotlightsQueryOptions,wE as getStatsQueryOptions,ww as getSubscribers,_w as getSubscriptions,UK as getSupportSettingsQueryOptions,zd as getSupportSettingsRequest,XR as getTradeHistoryQueryOptions,Uh as getTransactionsInfiniteQueryOptions,y_ as getTrendingTagsQueryOptions,A_ as getTrendingTagsWithStatsQueryOptions,Q_ as getUserPostVoteQueryOptions,hC as getUserProposalVotesQueryOptions,BC as getVestingDelegationExpirationsQueryOptions,CC as getVestingDelegationsQueryOptions,Si as getVisibleFirstLevelThreadItems,mv as getWavesByAccountQueryOptions,zb as getWavesByHostQueryOptions,ev as getWavesByTagQueryOptions,Kb as getWavesFeedQueryOptions,ov as getWavesFollowingQueryOptions,Bb as getWavesLatestFeedQueryOptions,_v as getWavesTrendingAuthorsQueryOptions,uv as getWavesTrendingTagsQueryOptions,ZC as getWithdrawRoutesQueryOptions,BD as getWitnessVoterCountQueryOptions,KD as getWitnessVotersPageQueryOptions,DD as getWitnessesInfiniteQueryOptions,wp as hasThreeSpeakEmbed,S as hiveTxConfig,ie as hiveTxUtils,OB as hsTokenRenew,k as invalidateAfterBroadcast,ri as isCommunity,ni as isEmptyDate,Ds as isInfoError,Ks as isNetworkError,We as isQueryableAccountName,Is as isResourceCreditsError,$x as isThreeSpeakBeneficiary,cp as isVoteAlreadyReflected,Wn as isWif,Ws as isWrappedResponse,Hy as lookupAccountsQueryOptions,cg as makeQueryClient,RB as mapMetaChoicesToPollChoices,ki as mapThreadItemsToWaveEntries,Qi as markNotifications,Lp as measureQuestContentLength,zi as moveSchedule,bi as normalizePost,Cd as normalizeSearchAuthor,Td as normalizeSearchCategory,Rd as normalizeSearchTags,ae as normalizeToWrappedResponse,ye as normalizeWaveEntryFromApi,j0 as onboardEmail,It as parseAccounts,T as parseAsset,je as parseChainError,ua as parsePostingMetadataRoot,Be as parseProfileMetadata,ai as pickRicherMetadataSnapshot,LP as powerRechargeTime,Xv as proMembersSet,WP as rcPower,Ji as removeOptimisticDiscussionEntry,Hl as resolveAccountHistoryLimit,gt as resolveHiveOperationFilters,gi as resolvePost,Yi as restoreDiscussionSnapshots,rx as restoreEntryInCache,yk as roleMap,Q0 as saveNotificationSetting,pK as search,lK as searchPath,oK as searchQueryOptions,Im as sha256,we as shouldTriggerAuthFallback,K0 as signUp,Co as similar,rc as sortDiscussions,B0 as subscribeEmail,Ac as toEntryArray,Li as updateDraft,tx as updateEntryInCache,Xd as updateSupportSettingsRequest,Ui as uploadImage,U0 as uploadImageWithSignature,$A as useAccountFavoriteAdd,YA as useAccountFavoriteDelete,uA as useAccountRelationsUpdate,kP as useAccountRevokeKey,fP as useAccountRevokePosting,iA as useAccountUpdate,Di as useAccountUpdateKeyAuths,aP as useAccountUpdatePassword,bP as useAccountUpdateRecovery,z0 as useAddDraft,b0 as useAddFragment,EO as useAddImage,lO as useAddSchedule,zg as useAiAssist,Zg as useAiTranscribe,NA as useBookmarkAdd,UA as useBookmarkDelete,hB as useBoostPlus,v as useBroadcastMutation,cS as useBuyStreakFreeze,FP as useClaimAccount,aD as useClaimEngineRewards,KI as useClaimInterest,jD as useClaimPoints,HI as useClaimRewards,YO as useComment,RI as useConvert,QP as useCreateAccount,lx as useCrossPost,LI as useDelegateEngineToken,vD as useDelegateRc,Yq as useDelegateVestingShares,ax as useDeleteComment,sO as useDeleteDraft,RO as useDeleteImage,yO as useDeleteSchedule,S0 as useEditFragment,lD as useEngineMarketOrder,TA as useFollow,zE as useGameClaim,Lg as useGenerateImage,KP as useGrantPostingPermission,mF as useLimitOrderCancel,pF as useLimitOrderCreate,zk as useMarkNotificationsRead,vO as useMoveSchedule,bS as useMutePost,KS as usePinPost,MB as usePollVote,wx as usePromote,xC as useProposalCreate,vC as useProposalVote,vB as useRcDelegation,WO as useReblog,zr as useRecordActivity,FS as useRegisterCommunityRewards,q0 as useRemoveFragment,OS as useSetCommunityRole,Zk as useSetLastRead,rI as useSetWithdrawVestingRoute,c0 as useSignOperationByHivesigner,t0 as useSignOperationByKey,i0 as useSignOperationByKeychain,ZI as useStakeEngineToken,dS as useSubscribeCommunity,Hq as useTransfer,sI as useTransferEngineToken,yI as useTransferFromSavings,$q as useTransferPoint,lI as useTransferToSavings,vI as useTransferToVesting,zI as useUndelegateEngineToken,IA as useUnfollow,nD as useUnstakeEngineToken,yS as useUnsubscribeCommunity,kS as useUpdateCommunity,eO as useUpdateDraft,gx as useUpdateReply,WK as useUpdateSupportSettings,DO as useUploadImage,UO as useVote,hD as useWalletOperation,EI as useWithdrawVesting,CD as useWitnessProxy,xD as useWitnessVote,N0 as usrActivity,gr as utf8ByteLength,fp as validatePostCreating,$e as varintByteLength,fi as verifyPostOnAlternateNode,Le as vestsToHp,jP as votingPower,Bu as votingRshares,GP as votingValue,ve as withTimeoutSignal};//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/sdk/dist/browser/index.js.map b/packages/sdk/dist/browser/index.js.map index d832461cbe..e7300da2fc 100644 --- a/packages/sdk/dist/browser/index.js.map +++ b/packages/sdk/dist/browser/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","_ByteBuffer","capacity","littleEndian","__publicField","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","ByteBuffer","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","expiration","props","refBlockPrefix","expirationIso","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","count","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"],"mappings":"yqBASA,IAAMA,EAAAA,CAAe,IAAI,YAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,EAAAA,EAAgD,CACvD,OAAKF,EAAAA,GACC,OAAO,YAAgB,GAAA,CACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,OAAOG,CAAAA,CAAuB,CAE5B,IAAMC,CAAAA,CAAiB,GACvB,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,IAAK,CACjC,IAAIC,EAAIH,CAAAA,CAAE,UAAA,CAAWE,CAAC,CAAA,CACtB,GAAIC,EAAI,GAAA,CACNF,CAAAA,CAAK,KAAKE,CAAC,CAAA,CAAA,KAAA,GACFA,EAAI,IAAA,CACbF,CAAAA,CAAK,KAAK,GA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F","file":"index.js","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/core/utf8.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts","../../src/modules/resource-credits/types/resource-params.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/resource-credits/utils/estimate-comment-rc-cost.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","_ByteBuffer","capacity","littleEndian","__publicField","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","ByteBuffer","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","expiration","props","refBlockPrefix","expirationIso","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","utf8ByteLength","varintByteLength","count","remaining","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","getRcResourceParamsQueryOptions","RC_RESOURCE_NAMES","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","TRANSACTION_HEADER_BYTES","SIGNATURE_BYTES","ASSET_BYTES","big","computeResourceCost","curve","pool","resourceCount","regenShare","coeffA","coeffB","shift","denom","countCommentResourceUsage","transactionBytes","permlinkLength","signatures","hasCommentOptions","sizeInfo","state","exec","stringFieldBytes","commentOperationBytes","commentOptionsBytes","route","estimateCommentTransactionBytes","estimateCommentRcCost","rcParams","usage","regen","cost","breakdown","share","scaled","resourceCost","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"],"mappings":"yqBASA,IAAMA,EAAAA,CAAe,IAAI,YAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,EAAAA,EA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,CAAA,CACA,MAAA,CACA7yC,CAAAA,CACA,SAAA,CACA,CAAE,aAAA,CAAeI,CAAAA,EAAiB,OAAQ,CAC5C,CACF","file":"index.js","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n resourceParams: () => [\"resource-credits\", \"resource-params\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","/**\n * UTF-8 byte length of a string.\n *\n * `TextEncoder` is missing on some runtimes the SDK ships to (React Native /\n * Hermes), and `String.length` is NOT a substitute: it counts UTF-16 code\n * units, so anything non-ASCII is undercounted. Where that number feeds an RC\n * estimate, undercounting means telling someone a post is affordable when the\n * chain will reject it.\n */\nexport function utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).length;\n }\n\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const c = value.charCodeAt(i);\n if (c < 0x80) {\n bytes += 1;\n } else if (c < 0x800) {\n bytes += 2;\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < value.length) {\n // surrogate pair encodes as four bytes\n i++;\n bytes += 4;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n\n/** Byte length of Hive's unsigned LEB128 varint for `value`. */\nexport function varintByteLength(value: number): number {\n let count = 0;\n let remaining = value;\n do {\n count++;\n remaining >>>= 7;\n } while (remaining > 0);\n return count;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { RcResourceParams } from \"../types/resource-params\";\n\n/**\n * Curve coefficients and sizing constants used to price resource usage.\n *\n * These only change at a hardfork, so the entry is kept for the session:\n * `gcTime: Infinity` is the one value that schedules no gc timer at all, so it\n * does not hold a request's query cache open on the server the way a long\n * finite window would.\n *\n * `staleTime` stays bounded on purpose. Making it infinite too would mean a\n * long-lived session keeps pricing with pre-hardfork coefficients forever,\n * quietly producing wrong RC estimates with no way to recover short of a\n * reload. A day is long enough that this is effectively never refetched, and\n * short enough that a hardfork corrects itself.\n */\nexport function getRcResourceParamsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.resourceCredits.resourceParams(),\n staleTime: 24 * 60 * 60 * 1000,\n gcTime: Infinity,\n queryFn: async () => (await callRPC(\"rc_api.get_resource_params\", {})) as RcResourceParams\n });\n}\n","/** Shape returned by `rc_api.get_resource_params`. Numbers arrive as strings. */\nexport interface RcPriceCurveParams {\n coeff_a: string | number;\n coeff_b: string | number;\n shift: string | number;\n}\n\nexport interface RcResourceDynamicsParams {\n resource_unit: string | number;\n budget_per_time_unit: string | number;\n pool_eq: string | number;\n max_pool_size: string | number;\n}\n\nexport interface RcResourceParamEntry {\n resource_dynamics_params: RcResourceDynamicsParams;\n price_curve_params: RcPriceCurveParams;\n}\n\n/**\n * Per-operation and per-transaction sizing constants. Only the members this\n * module needs are declared; the node returns many more.\n */\nexport interface RcSizeInfo {\n resource_state_bytes: {\n comment_base_size: number;\n comment_permlink_char_size: number;\n comment_beneficiaries_member_size: number;\n transaction_base_size: number;\n [key: string]: number;\n };\n resource_execution_time: {\n comment_time: number;\n comment_options_time: number;\n transaction_time: number;\n verify_authority_time: number;\n [key: string]: number;\n };\n [key: string]: Record;\n}\n\nexport interface RcResourceParams {\n resource_params: Record;\n size_info: RcSizeInfo;\n}\n\n/**\n * Resource order is consensus-defined (`HIVE_RC_NUM_RESOURCE_TYPES`) and the\n * `pool`, `share` and `budget` arrays in rc_stats are indexed by it.\n */\nexport const RC_RESOURCE_NAMES = [\n \"resource_history_bytes\",\n \"resource_new_accounts\",\n \"resource_market_bytes\",\n \"resource_state_bytes\",\n \"resource_execution_time\"\n] as const;\n\nexport type RcResourceName = (typeof RC_RESOURCE_NAMES)[number];\n\nexport interface RcCostBreakdown {\n resource: RcResourceName;\n usage: number;\n cost: number;\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcPriceCurveParams,\n type RcResourceName,\n type RcResourceParams,\n type RcSizeInfo\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * What the chain actually charges for publishing a comment, rather than the\n * network-average cost of an average comment.\n *\n * The average is a poor guide for posts: it is dominated by short replies,\n * while a long post is charged mostly on `history_bytes`, which is the\n * serialized transaction size. A real case: an account holding 21.3B RC was\n * told it could afford 17 posts, then a 46,620-byte post was rejected needing\n * 23.3B RC, more than that account's entire maximum.\n *\n * This is a direct port of `resource_credits::compute_cost` and the\n * `comment_operation` arm of `count_resources` from hive, so it tracks what\n * the node does instead of approximating it. Verified against a real\n * rejection: usage reproduces exactly and total cost lands within 0.3%, the\n * residual coming from `share` being published rounded to four digits.\n */\n\n/**\n * Fixed transaction header: ref_block_num(2) + ref_block_prefix(4) +\n * expiration(4) + the extensions varint(1).\n */\nconst TRANSACTION_HEADER_BYTES = 11;\n/** Compact signature, 65 bytes each. */\nconst SIGNATURE_BYTES = 65;\n/** asset = amount int64(8) + precision(1) + symbol(7). */\nconst ASSET_BYTES = 16;\n\nconst big = (v: string | number): bigint => BigInt(typeof v === \"string\" ? v : Math.trunc(v));\n\n/**\n * Port of `resource_credits::compute_cost` (libraries/chain/rc/rc_utility.cpp).\n *\n * BigInt is required, not stylistic: `coeff_a` is ~1.05e19, well past\n * Number.MAX_SAFE_INTEGER, so float arithmetic loses the low bits and the\n * result drifts.\n */\nexport function computeResourceCost(\n curve: RcPriceCurveParams,\n pool: number,\n resourceCount: number,\n regenShare: number\n): number {\n if (resourceCount <= 0 || regenShare <= 0) {\n return 0;\n }\n\n const coeffA = big(curve.coeff_a);\n const coeffB = big(curve.coeff_b);\n const shift = big(curve.shift);\n\n // The node shifts before multiplying by the resource count, because\n // regen * coeff_a already risks overflowing 128 bits. Order matters.\n let num = (big(regenShare) * coeffA) >> shift;\n num += 1n;\n num *= big(resourceCount);\n\n const denom = coeffB + (pool > 0 ? big(pool) : 0n);\n if (denom === 0n) {\n return 0;\n }\n\n return Number(num / denom + 1n);\n}\n\nexport interface CommentResourceUsageInput {\n /** Byte length of the serialized transaction. */\n transactionBytes: number;\n permlinkLength: number;\n /** Signatures on the transaction; a normal post carries one. */\n signatures?: number;\n /**\n * Beneficiary count on the companion comment_options, when publish appends\n * one. The chain counts resources for every operation in the transaction,\n * not just the comment.\n */\n beneficiaries?: number;\n hasCommentOptions?: boolean;\n}\n\n/**\n * Port of the `comment_operation` and `comment_options_operation` arms of\n * `count_resources` (libraries/chain/rc/resource_count.cpp). Reproduces the\n * chain's numbers exactly, see the spec.\n */\nexport function countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength,\n signatures = 1,\n beneficiaries = 0,\n hasCommentOptions = false\n }: CommentResourceUsageInput,\n sizeInfo: RcSizeInfo\n): Record {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n resource_history_bytes: transactionBytes,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes:\n state.comment_base_size +\n state.comment_permlink_char_size * permlinkLength +\n state.transaction_base_size +\n // comment_payout_beneficiaries is visited from comment_options\n state.comment_beneficiaries_member_size * beneficiaries,\n resource_execution_time:\n exec.comment_time +\n exec.transaction_time +\n exec.verify_authority_time * signatures +\n (hasCommentOptions ? exec.comment_options_time : 0)\n };\n}\n\nexport interface CommentLike {\n author: string;\n permlink: string;\n parent_author: string;\n parent_permlink: string;\n title: string;\n body: string;\n json_metadata: string;\n}\n\n\n/** A beneficiary route as it appears in comment_options extensions. */\nexport interface BeneficiaryRoute {\n account: string;\n weight: number;\n}\n\n/**\n * The comment_options operation publish appends when the author sets\n * beneficiaries or a non-default reward split.\n */\nexport interface CommentOptionsLike {\n beneficiaries?: BeneficiaryRoute[];\n}\n\n/** Serialized bytes of one string field: its varint length plus its bytes. */\nconst stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst commentOperationBytes = (op: CommentLike): number =>\n 1 + // operation variant id\n stringFieldBytes(op.parent_author) +\n stringFieldBytes(op.parent_permlink) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n stringFieldBytes(op.title) +\n stringFieldBytes(op.body) +\n stringFieldBytes(op.json_metadata);\n\nconst commentOptionsBytes = (op: CommentLike, options: CommentOptionsLike): number => {\n const beneficiaries = options.beneficiaries ?? [];\n let bytes =\n 1 + // operation variant id\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n ASSET_BYTES + // max_accepted_payout\n 2 + // percent_hbd\n 2; // allow_votes + allow_curation_rewards\n\n bytes += varintByteLength(beneficiaries.length > 0 ? 1 : 0);\n if (beneficiaries.length > 0) {\n bytes += 1 + varintByteLength(beneficiaries.length); // extension variant id + route count\n beneficiaries.forEach((route) => {\n bytes += stringFieldBytes(route.account) + 2; // weight is uint16\n });\n }\n return bytes;\n};\n\nexport interface CommentTransactionInput {\n op: CommentLike;\n /** Present when publish appends comment_options for beneficiaries or rewards. */\n options?: CommentOptionsLike;\n signatures?: number;\n}\n\n/**\n * Serialized size of the transaction that will carry this comment.\n *\n * This models Hive's binary encoding rather than approximating it: a fixed\n * header, one varint-prefixed field per string, and 65 bytes per signature.\n * Verified byte-exact against eight real transactions read back with\n * `get_transaction_hex`, including one carrying comment_options.\n */\nexport function estimateCommentTransactionBytes({\n op,\n options,\n signatures = 1\n}: CommentTransactionInput): number {\n const operations = [commentOperationBytes(op)];\n if (options) {\n operations.push(commentOptionsBytes(op, options));\n }\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(operations.length) +\n operations.reduce((sum, bytes) => sum + bytes, 0) +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\nexport interface EstimateCommentRcCostInput {\n op: CommentLike;\n /** Companion comment_options, when the author set beneficiaries or rewards. */\n options?: CommentOptionsLike;\n rcParams: RcResourceParams | undefined;\n rcStats: Pick | undefined;\n signatures?: number;\n}\n\nexport interface CommentRcCostEstimate {\n /** False until both queries have resolved; callers must not warn on this. */\n ready: boolean;\n cost: number;\n transactionBytes: number;\n breakdown: RcCostBreakdown[];\n}\n\nconst EMPTY: CommentRcCostEstimate = {\n ready: false,\n cost: 0,\n transactionBytes: 0,\n breakdown: []\n};\n\n/** Total RC the chain will charge to broadcast this comment. */\nexport function estimateCommentRcCost({\n op,\n options,\n rcParams,\n rcStats,\n signatures = 1\n}: EstimateCommentRcCostInput): CommentRcCostEstimate {\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats?.pool || !rcStats.share) {\n return EMPTY;\n }\n\n const transactionBytes = estimateCommentTransactionBytes({ op, options, signatures });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: utf8ByteLength(op.permlink),\n signatures,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n\n const regen = Number(rcStats.regen);\n let cost = 0;\n const breakdown: RcCostBreakdown[] = [];\n\n RC_RESOURCE_NAMES.forEach((name, index) => {\n const entry = rcParams.resource_params[name];\n const pool = Number(rcStats.pool[index] ?? 0);\n const share = Number(rcStats.share[index] ?? 0);\n if (!entry || share <= 0) {\n return;\n }\n\n // `usage` is scaled by the resource unit before pricing. It is 1 for the\n // resources a comment touches, but market bytes and new accounts are not.\n const scaled = usage[name] * Number(entry.resource_dynamics_params.resource_unit ?? 1);\n // rc_stats publishes `share` as weight/divisor scaled to 10,000. Kept in\n // BigInt: regen is ~2.4e12 and the product is past the safe-integer range\n // for larger shares.\n const regenShare = Number((BigInt(regen) * BigInt(share)) / 10000n);\n const resourceCost = computeResourceCost(entry.price_curve_params, pool, scaled, regenShare);\n\n cost += resourceCost;\n breakdown.push({ resource: name, usage: scaled, cost: resourceCost });\n });\n\n return { ready: true, cost, transactionBytes, breakdown };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file diff --git a/packages/sdk/dist/node/index.cjs b/packages/sdk/dist/node/index.cjs index 412902d2b6..87163d4ecb 100644 --- a/packages/sdk/dist/node/index.cjs +++ b/packages/sdk/dist/node/index.cjs @@ -1,10 +1,10 @@ -'use strict';var reactQuery=require('@tanstack/react-query'),utils_js=require('@noble/hashes/utils.js'),legacy_js=require('@noble/hashes/legacy.js'),rn=require('bs58'),secp256k1_js=require('@noble/curves/secp256k1.js'),sha2_js=require('@noble/hashes/sha2.js'),aes_js=require('@noble/ciphers/aes.js'),jn=require('hivesigner');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var rn__default=/*#__PURE__*/_interopDefault(rn);var jn__default=/*#__PURE__*/_interopDefault(jn);var Ao=Object.defineProperty;var mt=(e,t)=>{for(var r in t)Ao(e,r,{get:t[r],enumerable:true});};var gt=new ArrayBuffer(0),yt=null,ht=null;function Po(){return yt||(typeof TextEncoder<"u"?yt=new TextEncoder:yt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),yt}function Jr(){return ht||(typeof TextDecoder<"u"?ht=new TextDecoder:ht={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),ht}var I=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?gt:new ArrayBuffer(t),this.view=t===0?new DataView(gt):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(gt));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof e?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,i=new e(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?gt:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=Po().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=Jr().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=Jr().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};var x={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},$t=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Wt=e=>{let t=$t(e);t.length&&(x.nodes=t);},Gt=e=>{let t=$t(e);t.length&&(x.restNodes=t);},zt=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=$t(n);i.length?t[r]=i:delete t[r];}x.restNodesByApi=t;},Jt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},Yt=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var Ae=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=utils_js.hexToBytes(t),n=parseInt(utils_js.bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return utils_js.bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=utils_js.hexToBytes(t));let r=secp256k1_js.secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1_js.secp256k1.Signature(r.r,r.s,this.recovery);return new J(n.recoverPublicKey(t).toBytes())}};var J=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??x.address_prefix;}static fromString(t){let r=x.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=rn__default.default.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=legacy_js.ripemd160(o).subarray(0,4);if(!xo(s,a))throw new Error("Public key checksum mismatch");try{secp256k1_js.secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Ae.from(r)),secp256k1_js.secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Oo(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Oo=(e,t)=>{let r=legacy_js.ripemd160(e);return t+rn__default.default.encode(new Uint8Array([...e,...r.subarray(0,4)]))},xo=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},_=(e,t)=>{e.writeVString(t);},ko=(e,t)=>{e.writeInt16(t);},on=(e,t)=>{e.writeInt64(t);},nn=(e,t)=>{e.writeUint8(t);},ue=(e,t)=>{e.writeUint16(t);},Y=(e,t)=>{e.writeUint32(t);},sn=(e,t)=>{e.writeUint64(t);},ge=(e,t)=>{e.writeByte(t?1:0);},an=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},q=(e,t)=>{let r=wt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},Pe=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},fe=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(J.from(t).key);},un=(e=null)=>(t,r)=>{r=_t.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},cn=un(),Xt=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ce=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},ke=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=ce([["weight_threshold",Y],["account_auths",Xt(_,ue)],["key_auths",Xt(fe,ue)]]),Co=ce([["account",_],["weight",ue]]),Zt=ce([["base",q],["quote",q]]),To=ce([["account_creation_fee",q],["maximum_block_size",Y],["hbd_interest_rate",ue]]),R=(e,t)=>{let r=ce(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},k={};k.account_create=R(T.account_create,[["fee",q],["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_]]);k.account_create_with_delegation=R(T.account_create_with_delegation,[["fee",q],["delegation",q],["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_],["extensions",V(ie)]]);k.account_update=R(T.account_update,[["account",_],["owner",ke(W)],["active",ke(W)],["posting",ke(W)],["memo_key",fe],["json_metadata",_]]);k.account_witness_proxy=R(T.account_witness_proxy,[["account",_],["proxy",_]]);k.account_witness_vote=R(T.account_witness_vote,[["account",_],["witness",_],["approve",ge]]);k.cancel_transfer_from_savings=R(T.cancel_transfer_from_savings,[["from",_],["request_id",Y]]);k.change_recovery_account=R(T.change_recovery_account,[["account_to_recover",_],["new_recovery_account",_],["extensions",V(ie)]]);k.claim_account=R(T.claim_account,[["creator",_],["fee",q],["extensions",V(ie)]]);k.claim_reward_balance=R(T.claim_reward_balance,[["account",_],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);k.comment=R(T.comment,[["parent_author",_],["parent_permlink",_],["author",_],["permlink",_],["title",_],["body",_],["json_metadata",_]]);k.comment_options=R(T.comment_options,[["author",_],["permlink",_],["max_accepted_payout",q],["percent_hbd",ue],["allow_votes",ge],["allow_curation_rewards",ge],["extensions",V(an([ce([["beneficiaries",V(Co)]])]))]]);k.convert=R(T.convert,[["owner",_],["requestid",Y],["amount",q]]);k.create_claimed_account=R(T.create_claimed_account,[["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_],["extensions",V(ie)]]);k.custom=R(T.custom,[["required_auths",V(_)],["id",ue],["data",cn]]);k.custom_json=R(T.custom_json,[["required_auths",V(_)],["required_posting_auths",V(_)],["id",_],["json",_]]);k.decline_voting_rights=R(T.decline_voting_rights,[["account",_],["decline",ge]]);k.delegate_vesting_shares=R(T.delegate_vesting_shares,[["delegator",_],["delegatee",_],["vesting_shares",q]]);k.delete_comment=R(T.delete_comment,[["author",_],["permlink",_]]);k.escrow_approve=R(T.escrow_approve,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Y],["approve",ge]]);k.escrow_dispute=R(T.escrow_dispute,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Y]]);k.escrow_release=R(T.escrow_release,[["from",_],["to",_],["agent",_],["who",_],["receiver",_],["escrow_id",Y],["hbd_amount",q],["hive_amount",q]]);k.escrow_transfer=R(T.escrow_transfer,[["from",_],["to",_],["hbd_amount",q],["hive_amount",q],["escrow_id",Y],["agent",_],["fee",q],["json_meta",_],["ratification_deadline",Pe],["escrow_expiration",Pe]]);k.feed_publish=R(T.feed_publish,[["publisher",_],["exchange_rate",Zt]]);k.limit_order_cancel=R(T.limit_order_cancel,[["owner",_],["orderid",Y]]);k.limit_order_create=R(T.limit_order_create,[["owner",_],["orderid",Y],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",ge],["expiration",Pe]]);k.limit_order_create2=R(T.limit_order_create2,[["owner",_],["orderid",Y],["amount_to_sell",q],["exchange_rate",Zt],["fill_or_kill",ge],["expiration",Pe]]);k.recover_account=R(T.recover_account,[["account_to_recover",_],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);k.request_account_recovery=R(T.request_account_recovery,[["recovery_account",_],["account_to_recover",_],["new_owner_authority",W],["extensions",V(ie)]]);k.reset_account=R(T.reset_account,[["reset_account",_],["account_to_reset",_],["new_owner_authority",W]]);k.set_reset_account=R(T.set_reset_account,[["account",_],["current_reset_account",_],["reset_account",_]]);k.set_withdraw_vesting_route=R(T.set_withdraw_vesting_route,[["from_account",_],["to_account",_],["percent",ue],["auto_vest",ge]]);k.transfer=R(T.transfer,[["from",_],["to",_],["amount",q],["memo",_]]);k.transfer_from_savings=R(T.transfer_from_savings,[["from",_],["request_id",Y],["to",_],["amount",q],["memo",_]]);k.transfer_to_savings=R(T.transfer_to_savings,[["from",_],["to",_],["amount",q],["memo",_]]);k.transfer_to_vesting=R(T.transfer_to_vesting,[["from",_],["to",_],["amount",q]]);k.vote=R(T.vote,[["voter",_],["author",_],["permlink",_],["weight",ko]]);k.withdraw_vesting=R(T.withdraw_vesting,[["account",_],["vesting_shares",q]]);k.witness_update=R(T.witness_update,[["owner",_],["url",_],["block_signing_key",fe],["props",To],["fee",q]]);k.witness_set_properties=R(T.witness_set_properties,[["owner",_],["props",Xt(_,cn)],["extensions",V(ie)]]);k.account_update2=R(T.account_update2,[["account",_],["owner",ke(W)],["active",ke(W)],["posting",ke(W)],["memo_key",ke(fe)],["json_metadata",_],["posting_json_metadata",_],["extensions",V(ie)]]);k.create_proposal=R(T.create_proposal,[["creator",_],["receiver",_],["start_date",Pe],["end_date",Pe],["daily_pay",q],["subject",_],["permlink",_],["extensions",V(ie)]]);k.update_proposal_votes=R(T.update_proposal_votes,[["voter",_],["proposal_ids",V(on)],["approve",ge],["extensions",V(ie)]]);k.remove_proposal=R(T.remove_proposal,[["proposal_owner",_],["proposal_ids",V(on)],["extensions",V(ie)]]);var Ro=ce([["end_date",Pe]]);k.update_proposal=R(T.update_proposal,[["proposal_id",sn],["creator",_],["daily_pay",q],["subject",_],["permlink",_],["extensions",V(an([ie,Ro]))]]);k.collateralized_convert=R(T.collateralized_convert,[["owner",_],["requestid",Y],["amount",q]]);k.recurrent_transfer=R(T.recurrent_transfer,[["from",_],["to",_],["amount",q],["memo",_],["recurrence",ue],["executions",ue],["extensions",V(ce([["type",nn],["value",ce([["pair_id",nn]])]]))]]);var Fo=(e,t)=>{let r=k[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},qo=ce([["ref_block_num",ue],["ref_block_prefix",Y],["expiration",Pe],["operations",V(Fo)],["extensions",V(_)]]),Io=ce([["from",fe],["to",fe],["nonce",sn],["check",Y],["encrypted",un()]]),pe={Asset:q,Memo:Io,Price:Zt,PublicKey:fe,String:_,Transaction:qo,UInt16:ue,UInt32:Y};var Xe=e=>new Promise(t=>setTimeout(t,e));var Do=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function fn(){return Do?{"User-Agent":x.userAgent}:{}}var X=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},Ce=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function mn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Ko=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Bo=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Mo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function No(e){if(!e)return false;if(e instanceof Ce)return true;if(e instanceof X)return false;let t=Mo(e);return !!(Ko.some(r=>t.includes(r))||Bo.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function er(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function gn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Qo=1e4,Ho=6e4,Uo=12e4,pn=2,ln=6e4,dn=12e4,Vo=30,Ze=.3,tr=3,et=5*6e4,yn=6e4,hn=1e3,wn=2e3,vt=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=tr&&i-o.updatedAt<=et?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>et&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:Ze*r+(1-Ze)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>et?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=Ze*r+(1-Ze)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=pn&&(o.cooldownUntil=i+ln),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,pn),o.lastFailureTime=i,o.cooldownUntil=i+ln,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>Uo&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(Qo*2**n.rateLimitStreak,Ho);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=dn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=dn&&o-n.headBlock>Vo)}getOrderedNodes(t,r){let n=[],i=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):i.push(c);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,o)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=tr&&r-t.latencyUpdatedAt<=et}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:hn}pickReprobeCandidate(t,r){let n=r-yn,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),c=Math.max(a.latencyUpdatedAt,a.lastProbeAt);c<=n&&c=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(x.resilience.hedgeBucketCapacity,this.tokens+x.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>x.resilience.hedgeBucketCapacity&&(this.tokens=x.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=x.resilience.hedgeBucketCapacity){this.tokens=t;}},nr=new rr;function At(e,t,r,n,i){let o=x.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function ir(e,t,r,n){r instanceof Ce?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof X?e.recordFailure(t,n):e.recordFailure(t);}function _n(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function jo(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function bn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(jo()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function or(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var tt=async(e,t,r,n=x.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=bn(n),{signal:l,cleanup:f}=or(c,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...fn()},signal:l});if(y.status===429)throw new Ce(e,"HTTP 429 Rate Limited",{rateLimitMs:mn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new Ce(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let E=h.error;throw "message"in E&&"code"in E?new X(E):h.error}throw h}catch(y){if(y instanceof X||y instanceof Ce||o?.aborted)throw y;if(i)return tt(e,t,r,n,false,o);throw y}finally{m();}};function bt(){return Xe(50+Math.random()*50)}function Lo(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,E=0,O=false,A=false,P,L,U=0,B=[],Q=z=>{if(!h){h=true,L!==void 0&&(clearTimeout(L),L=void 0);for(let F of B)F.signal.aborted||F.abort();z();}},$=(z,F)=>{E++;let de=new AbortController;B.push(de);let Ye=or(de.signal,p),vo=At(j,z,t,s,a),Lt=Date.now();F||(U=Lt),tt(z,t,r,vo,false,Ye.signal).then(ne=>{if(Ye.cleanup(),E--,F||(A=true),!h){if(f&&!f(ne)){if(j.recordDefectiveResponse(z,n),P=new Error(`[hive-tx] response validation failed for ${t} from ${z}`),!F&&!O){Q(()=>y(P));return}E===0&&Q(()=>y(P));return}j.recordSuccess(z,n,Date.now()-Lt,t),_n(j,z,t,ne),F?A||j.recordCensoredLatency(i,Date.now()-U,t):O||nr.refill(),Q(()=>m(ne));}}).catch(ne=>{if(Ye.cleanup(),E--,F||(A=true),!h){if(p?.aborted){Q(()=>y(ne));return}if(ne instanceof X&&!er(ne.code,ne.message)){Q(()=>y(ne));return}if(ir(j,z,ne,n),j.recordSlowFailure(z,Date.now()-Lt,t),P=ne,!F&&!O){Q(()=>y(ne));return}E===0&&Q(()=>y(P));}});};$(i,false);let Se=j.getUsableLatencyMs(i,t)??0,Je=At(j,i,t,s,a),jt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*Se),.8*Je);L=setTimeout(()=>{if(L=void 0,h||p?.aborted||Date.now()>=c)return;let z=o.filter(de=>j.isNodeHealthy(de,n));if(z.length===0)return;let F=z[Math.floor(Math.random()*z.length)];nr.trySpend()&&(O=true,l(F),$(F,true));},jt);})}var g=async(e,t=[],r,n=x.retry,i,o)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??x.timeout,c=gn(e),p=Date.now()+x.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=j.getOrderedNodes(x.nodes,c),h=y.find(A=>!l.has(A));h||(l.clear(),h=y[0]),l.add(h);let E=[];if(x.resilience.hedge&&j.getUsableLatencyMs(h,e)!==void 0&&(E=y.filter(A=>!l.has(A)&&j.isNodeHealthy(A,c)).slice(0,3)),E.length>0)try{return await Lo({method:e,params:t,api:c,primary:h,hedgePool:E,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:A=>l.add(A),validate:o})}catch(A){if(A instanceof X&&!er(A.code,A.message)||i?.aborted)throw A;f=A,m{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let i=gn(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await tt(p,e,t,r,!1,n);return j.recordSuccess(p,i),l}catch(l){if(l instanceof X||n?.aborted||(ir(j,p,l,i),s=l,!No(l)))throw l}}throw s},$o={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function ee(e,t,r,n,i=x.retry,o){if(!Array.isArray(x.restNodes))throw new Error("config.restNodes is not an array");if(x.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??x.timeout,c=Date.now()+x.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=x.restNodesByApi?.[e]?.length?x.restNodesByApi[e]:x.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=c);h++){let E=Oe.getOrderedNodes(l,e),O=E.find(F=>!f.has(F));O||(f.clear(),O=E[0]),f.add(O);let A=O+$o[e],P=t,L=r||{},U=new Set;Object.entries(L).forEach(([F,de])=>{P.includes(`{${F}}`)&&(P=P.replace(`{${F}}`,encodeURIComponent(String(de))),U.add(F));});let B=new URL(A+P);if(Object.entries(L).forEach(([F,de])=>{U.has(F)||(Array.isArray(de)?de.forEach(Ye=>B.searchParams.append(F,String(Ye))):B.searchParams.set(F,String(de)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:Q,cleanup:$}=bn(At(Oe,O,p,a,s)),{signal:Se,cleanup:Je}=or(Q,o),jt=()=>{$(),Je();},z=Date.now();try{let F=await fetch(B.toString(),{signal:Se,headers:fn()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw Oe.recordRateLimit(O,mn(F.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(F.status===503)throw Oe.recordFailure(O,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!F.ok)throw Oe.recordFailure(O,e),y=!0,new Error(`HTTP ${F.status} from ${O}`);return Oe.recordSuccess(O,e,Date.now()-z,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||o?.aborted)throw F;y||Oe.recordFailure(O,e),Oe.recordSlowFailure(O,Date.now()-z,p),m=F,h{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an Array");if(r>x.nodes.length)throw new Error("quorum > config.nodes.length");let o=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(x.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let c=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Wo(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Wo(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var zo=utils_js.hexToBytes(x.chain_id),Te=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Qe("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof X&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await Xe(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=utils_js.hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};}};var En=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1_js.secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(Zo(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=utils_js.hexToBytes(t);else {let n=[];for(let i=0;i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha2_js.sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1_js.secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(utils_js.bytesToHex(r.subarray(0,1)),16);return Ae.from((n+31).toString(16)+utils_js.bytesToHex(r.subarray(1)))}createPublic(t){return new J(secp256k1_js.secp256k1.getPublicKey(this.key),t)}toString(){return Xo(new Uint8Array([...En,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1_js.secp256k1.getSharedSecret(this.key,t.key);return sha2_js.sha512(r.subarray(1))}static randomKey(){return new e(secp256k1_js.secp256k1.keygen().secretKey)}},Sn=e=>sha2_js.sha256(sha2_js.sha256(e)),Xo=e=>{let t=Sn(e);return rn__default.default.encode(new Uint8Array([...e,...t.slice(0,4)]))},Zo=e=>{let t=rn__default.default.decode(e);if(!On(t.slice(0,1),En))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=Sn(n).slice(0,4);if(!On(r,i))throw new Error("Private key checksum mismatch");return n},On=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nRn(e,t,n,r),Tn=(e,t,r,n,i)=>Rn(e,t,r,n,i).message,Rn=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let c=sha2_js.sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),f=sha2_js.sha256(c).subarray(0,4),m=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=ns(n,l,p);}else n=is(n,l,p);return {nonce:o,message:n,checksum:y}},ns=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).decrypt(n),n},is=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).encrypt(n),n},ar=null,os=()=>{if(ar===null){let r=secp256k1_js.secp256k1.utils.randomSecretKey();ar=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++ar%65536;return e=e<{let t=ls(e,33);return new J(t)},as=e=>e.readUint64(),us=e=>e.readUint32(),cs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},ps=e=>t=>{let r={},n=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function ls(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var ds=ps([["from",Fn],["to",Fn],["nonce",as],["check",us],["encrypted",cs]]),qn={Memo:ds};var Dn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Bn(),e=Mn(e),t=fs(t);let i=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Cn(e,t,o,n),p=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);pe.Memo(p,{check:c,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+rn__default.default.encode(l)},Kn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Bn(),e=Mn(e);let r=qn.Memo(rn__default.default.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new J(n.key).toString()?new J(i.key):new J(n.key);r=Tn(e,p,o,a,s);let l=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Ot,Bn=()=>{if(Ot===void 0){let e;Ot=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Dn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Kn(t,n);}finally{Ot=e==="#memo\u7231";}}if(Ot===false)throw new Error("This environment does not support encryption.")},Mn=e=>typeof e=="string"?H.fromString(e):e,fs=e=>typeof e=="string"?J.fromString(e):e,Nn={decode:Kn,encode:Dn};var re={};mt(re,{buildWitnessSetProperties:()=>_s,makeBitMaskFilter:()=>hs,operations:()=>ys,validateUsername:()=>gs});var gs=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(ws,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),ws=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=pe.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=pe.UInt32;break;case "hbd_interest_rate":i=pe.UInt16;break;case "url":i=pe.String;break;case "hbd_exchange_rate":i=pe.Price;break;case "account_creation_fee":i=pe.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,bs(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},bs=(e,t)=>{let r=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return e(r,t),r.flip(),utils_js.bytesToHex(new Uint8Array(r.toBuffer()))};function um(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha2_js.sha256(t)}function Qn(e){try{return H.fromString(e),!0}catch{return false}}async function Z(e,t){let r=new Te;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Qe("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Hn(e,t){let r=new Te;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var As=432e3;function Un(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/As,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function Ps(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function ur(e){let t=Ps(e)*1e6;return Un(t,e.voting_manabar)}function xt(e){return Un(Number(e.max_rc),e.rc_manabar)}var Vn=(c=>(c.COMMON="common",c.INFO="info",c.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",c.MISSING_AUTHORITY="missing_authority",c.TOKEN_EXPIRED="token_expired",c.NETWORK="network",c.TIMEOUT="timeout",c.VALIDATION="validation",c))(Vn||{});function He(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Os(e){let t=He(e);return [t.message,t.type]}function ye(e){let{type:t}=He(e);return t==="missing_authority"||t==="token_expired"}function xs(e){let{type:t}=He(e);return t==="insufficient_resource_credits"}function Es(e){let{type:t}=He(e);return t==="info"}function Ss(e){let{type:t}=He(e);return t==="network"||t==="timeout"}async function he(e,t,r,n,i="posting",o,s,a="async"){let c=n?.adapter;switch(e){case "key":{if(!c)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(c.getOwnerKey)p=await c.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":c.getActiveKey&&(p=await c.getActiveKey(t));break;case "memo":if(c.getMemoKey)p=await c.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await c.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Hn(r,l):await Z(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new jn__default.default.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&ye(l))return await c.broadcastWithHiveSigner(t,r,i);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!c?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await c.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Cs(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await he(l,e,t,r,n,void 0,void 0,i)}catch(m){if(ye(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await he(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(ye(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await he(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await he(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let E;switch(n){case "owner":o.getOwnerKey&&(E=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(E=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(E=await o.getMemoKey(e));break;default:E=await o.getPostingKey(e);break}E?y=E:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let E=await o.getAccessToken(e);E&&(h=E);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await he(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!ye(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return reactQuery.useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async c=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(c);try{if(i?.enableFallback!==!1&&i?.adapter)return await Cs(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=H.fromString(l);return await Z(p,m)}let f=i?.accessToken;if(f)return (await new jn__default.default.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof X?new Error(l.message):l}}})}async function Ln(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let c=H.fromString(o);return Z([["custom_json",i]],c)}let s=n?.accessToken;if(s)return (await new jn__default.default.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,c,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,c,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Om=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function we(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var Re=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),Fs=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},_e=1e4,$n=120*1e3,Et,qs;function Is(){return Et?Et():qs??=new reactQuery.QueryClient}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:Fs(),get queryClient(){return Is()},set queryClient(e){Et=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false};exports.ConfigManager=void 0;(A=>{function e(P){d.queryClient=P;}A.setQueryClient=e;function t(P){Et=P;}A.setQueryClientResolver=t;function r(P){d.privateApiHost=P;}A.setPrivateApiHost=r;function n(P){d.clientId=P;}A.setClientId=n;function i(P){if(typeof P!="string"||P.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=P;}A.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}A.getValidatedBaseUrl=o;function s(P){d.pollsApiHost=P;}A.setPollsApiHost=s;function a(P){d.imageHost=P;}A.setImageHost=a;function c(P){Wt(P);}A.setHiveNodes=c;function p(P){Gt(P);}A.setRestNodes=p;function l(P){zt(P);}A.setRestNodesByApi=l;function f(P){Jt(P);}A.setUserAgent=f;function m(P){Yt(P);}A.setResilience=m;function y(P){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(P))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(P))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(P))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(P)||/\.\+\.\+/.test(P))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let L=/\.?\{(\d+),(\d+)\}/g,U;for(;(U=L.exec(P))!==null;){let[,B,Q]=U;if(parseInt(Q,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${Q}}`}}return {safe:true}}function h(P){let L=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],U=5;for(let B of L){let Q=Date.now();try{P.test(B);let $=Date.now()-Q;if($>U)return {safe:!1,reason:`runtime test exceeded ${U}ms (took ${$}ms on input length ${B.length})`}}catch($){return {safe:false,reason:`runtime test threw error: ${$}`}}}return {safe:true}}function E(P,L=200){try{if(!P)return Re&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(P.length>L)return Re&&console.warn(`[SDK] DMCA pattern rejected: length ${P.length} exceeds max ${L} - pattern: ${P.substring(0,50)}...`),null;let U=y(P);if(!U.safe)return Re&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${U.reason}) - pattern: ${P.substring(0,50)}...`),null;let B;try{B=new RegExp(P);}catch($){return Re&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${P.substring(0,50)}...`,$),null}let Q=h(B);return Q.safe?B:(Re&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Q.reason}) - pattern: ${P.substring(0,50)}...`),null)}catch(U){return Re&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${P.substring(0,50)}...`,U),null}}function O(P={}){let L=$=>Array.isArray($)?$.filter(Se=>typeof Se=="string"):[],U=P||{},B={accounts:L(U.accounts),tags:L(U.tags),patterns:L(U.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map($=>E($)).filter($=>$!==null),d.dmcaPatternRegexes=[];let Q=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Re&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${Q} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),Q>0&&console.warn(`[SDK] ${Q} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}A.setDmcaLists=O;})(exports.ConfigManager||={});function Km(){return new reactQuery.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient;exports.EcencyQueriesManager=void 0;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>reactQuery.useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>reactQuery.useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(exports.EcencyQueriesManager||={});function Mm(e){return btoa(JSON.stringify(e))}function Nm(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Wn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Wn||{}),St=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(St||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Wn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:St[e.nai]}}var cr;function w(){if(!cr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");cr=globalThis.fetch.bind(globalThis);}return cr}function Gn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Ns(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return Ns(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ue(e,t){return e/1e6*t}function zn(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var Jn=60*1e3;function be(){return reactQuery.queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:Jn,staleTime:Jn,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=C(t.total_vesting_shares).amount,a=C(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=C(r.current_median_history.base).amount,l=C(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=C(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",E=Number(i.content_constant??0),O=String(o.current_hardfork_version??"0.0.0"),A=Number(o.last_hardfork??0),P=t.hbd_print_rate,L=t.hbd_interest_rate,U=t.head_block_number,B=a,Q=s,$=C(t.virtual_supply).amount,Se=t.vesting_reward_percent||0,Je=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:E,currentHardforkVersion:O,lastHardfork:A,hbdPrintRate:P,hbdInterestRate:L,headBlock:U,totalVestingFund:B,totalVestingShares:Q,virtualSupply:$,vestingRewardPercent:Se,accountCreationFee:Je,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function tg(e="post"){return reactQuery.queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function Fe(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var u={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>Fe("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Fe("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Fe("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Fe("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>Fe("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>Fe("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>Fe("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function sg(e){return reactQuery.queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await w()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function pg(e,t){return reactQuery.queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function mg(e,t){return reactQuery.queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function $s(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function wg(e,t){return reactQuery.useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??$s()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw c.status=i.status,c.data=a,c}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Gs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ag(e,t){return reactQuery.useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Gs()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Js(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Eg(e,t){return reactQuery.useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??Js()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await w()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),c={};try{c=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:c})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function pr(e){return !e.posting_json_metadata&&!e.json_metadata}function Xs(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function M(e){return reactQuery.queryOptions({queryKey:u.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(pr(i)&&Xs(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!pr(l[0])));if(p[0]&&!pr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=qe(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:c,profile:o}},enabled:!!e,staleTime:6e4})}var Zs=new Set(["__proto__","constructor","prototype"]);function kt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Yn(e,t){let r={...e};for(let n of Object.keys(t)){if(Zs.has(n))continue;let i=t[n],o=r[n];kt(i)&&kt(o)?r[n]=Yn(o,i):r[n]=i;}return r}function ea(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function qe(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function Xn(e){return qe(e?.posting_json_metadata)}function Zn(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(qe(e.posting_json_metadata)).length;return Object.keys(qe(t.posting_json_metadata)).length>r?t:e}function ta(e){if(!e)return {};try{let t=JSON.parse(e);if(kt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ei({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=ta(e),i=kt(n.profile)?n.profile:{},o=lr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function lr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=Yn(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=ea(s.tokens),s.version=2,s}function Ct(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=qe(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function ra(e){return new TextEncoder().encode(e).length}function Ve(e){return e?ra(e)<=16:false}function Ug(e){return reactQuery.queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Ve);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ct(r??[])}})}function Wg(e){return reactQuery.queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function Xg(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function ny(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var ti=1e3,ua=20;function uy(e){return reactQuery.queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthVe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function _y(e,t=5,r=[]){return reactQuery.queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var da=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Py(e,t){return reactQuery.queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await w()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,c=typeof a.token=="string"?a.token:void 0;if(!c)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:c,currency:c,address:f,show:y,type:"CHAIN",meta:l},E=[];for(let[O,A]of Object.entries(p))typeof O=="string"&&(da.has(O)||typeof A!="string"||!A||/^[A-Z0-9]{2,10}$/.test(O)&&E.push({symbol:O,currency:O,address:A,show:y,type:"CHAIN",meta:{address:A,show:y}}));return [h,...E]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function ri(e,t){return reactQuery.queryOptions({queryKey:u.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function Fy(e){return reactQuery.queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Ky(e,t){return reactQuery.queryOptions({queryKey:u.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function By(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Hy(e,t){return reactQuery.queryOptions({queryKey:u.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Uy(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function $y(e,t,r){return reactQuery.queryOptions({queryKey:u.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await w()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function Jy(e,t){return reactQuery.queryOptions({enabled:!!e&&!!t,queryKey:u.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await w()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function th(e){return reactQuery.queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function ah(e,t=50){return reactQuery.queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Ve(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var D=re.operations,ni={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.fill_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay]},Oa=Array.from(new Set(Object.values(ni).flat()));function xa(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ea(e){return e.replace(/_operation$/,"")}function Sa(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function ka(e){if(!Sa(e))return e;let t=C(e),r=St[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Ca(e){let t={};for(let[r,n]of Object.entries(e))t[r]=ka(n);return t}function gh(e,t=20,r=""){let n=r?ni[r]:Oa;return reactQuery.infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await ee("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ea(m.op.type);return {...Ca(m.op.value),num:xa(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(i),p=a(c),l=i??c.total_pages;if(i===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function _h(){return reactQuery.queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Ph(e){return reactQuery.infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=exports.ConfigManager.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Sh(e){return reactQuery.queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function qh(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Da=30;function Mh(e,t,r){return reactQuery.queryOptions({queryKey:u.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(c=>t==="following"?c.following:c.follower).filter(c=>c.toLowerCase().includes(r.toLowerCase())).slice(0,Da);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(c=>({name:c.name,full_name:c.metadata.profile?.name||"",reputation:c.reputation,active:c.active}))??[]}})}function Vh(e=20){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function zh(e=250){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Gn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function je(e,t){return reactQuery.queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await w()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function Zh(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function nw(e="feed"){return reactQuery.queryOptions({queryKey:u.posts.promoted(e),queryFn:async()=>{let t=exports.ConfigManager.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await w()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function uw(e){return reactQuery.queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function fw(e,t,r){return reactQuery.queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function ww(e,t){return reactQuery.queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function Pw(e,t){return reactQuery.queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function kw(e,t){return reactQuery.queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function te(e){return Array.isArray(e)?e.map(t=>ii(t)):ii(e)}function ii(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function oi(e,t,r){try{let n=await Pt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function si(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return reactQuery.queryOptions({queryKey:u.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let c=await oi(e,i,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return te(p)}let a=n!==void 0?{...s,num:n}:s;return te(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function se(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function ai(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await Wa(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function ui(e,t,r){let n=e.map(nt),i=await Promise.all(n.map(o=>ai(o,t,void 0,r)));return te(i)}async function ci(e,t="",r="",n=20,i="",o="",s){let a=await se("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?ui(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function dr(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await se("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?ui(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function nt(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Wa(e="",t="",r="",n,i){let o=await se("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=nt(o),a=await ai(s,r,n,i);return te(a)}}async function Vw(e="",t=""){let r=await se("get_post_header",{author:e,permlink:t});return r&&nt(r)}async function pi(e,t,r){let n=await se("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=nt(s);return i}return n}async function li(e,t=""){return se("get_community",{name:e,observer:t})}async function jw(e="",t=100,r,n="rank",i=""){return se("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function di(e){let t=await se("normalize_post",{post:e});return t&&nt(t)}async function Lw(e){return se("list_all_subscriptions",{account:e})}async function $w(e){return se("list_subscribers",{community:e})}async function Ww(e,t){return se("get_relationship_between_accounts",[e,t])}async function Tt(e,t){return se("get_profiles",{accounts:e,observer:t})}var mi=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(mi||{});function fr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Ga(e,t,r){let n=l=>fr(l.pending_payout_value).amount+fr(l.author_payout_value).amount+fr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function gi(e,t="created",r=true,n){let i=n||d.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return te(s)},enabled:r&&!!e,select:o=>Ga(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),c=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!c.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function e_(e,t,r,n=true){let i=r||d.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>pi(e,t,i)})}function a_(e,t="posts",r=20,n="",i=true){return reactQuery.infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await dr(t,e,o.author??"",o.permlink??"",r,n,s);return te(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function u_(e,t="posts",r="",n="",i=20,o="",s=true){return reactQuery.queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await dr(t,e,r,n,i,o,a);return te(c??[])}})}var yi=new Map;function Za(e){let t=yi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>eu(n,e))}),yi.set(e,t)),t}function eu(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function y_(e,t,r=20,n="",i=true,o={}){return reactQuery.infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:c,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return te(p)},select:Za(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function h_(e,t="",r="",n=20,i="",o="",s=true){return reactQuery.queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let c=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(c="");let p=await ci(e,t,r,n,c,o,a);return te(p??[])}})}function A_(e,t,r=200){return reactQuery.queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function S_(e,t){return reactQuery.queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function R_(e,t){return reactQuery.queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function F_(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function K_(e,t){return reactQuery.queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function B_(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function wi(e){let r=await w()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function H_(e,t){return reactQuery.queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:wi(t),enabled:!!e&&!!t})}function U_(e,t){return reactQuery.queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:wi(t),enabled:!!e&&!!t})}function V_(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:u.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function W_(e,t,r=false){return reactQuery.queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function pu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function Y_(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?pu(n,r):"";return reactQuery.queryOptions({queryKey:u.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:c,tags:p}=s.list[0];return {body:a,title:c,tags:p}},enabled:i})}function tb(e,t,r=true){return reactQuery.queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function du(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function fu(e){return {...e,id:e.id??e.post_id}}function me(e,t){if(!e)return null;let r=e.container??e,n=du(r,t),i=e.parent?fu(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function mu(e){return Array.isArray(e)?e:[]}async function _i(e){let t=gi(e,"created",true),r=await d.queryClient.fetchQuery(t),n=mu(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function bi(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var hu=20;function vi(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??hu}}async function Ai({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let c=exports.ConfigManager.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=me(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function cb(e={}){let t=vi(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Ai(t,c,p),getNextPageParam:c=>{if(!(c.lengthAi(t,void 0,c)})}var _u=20;function bu(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??_u}}async function vu({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=exports.ConfigManager.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(i)),o&&c.searchParams.set("cursor",o),e.forEach(f=>c.searchParams.append("container",f)),t&&c.searchParams.set("tag",t),r&&c.searchParams.set("author",r),n&&c.searchParams.set("observer",n);let p=await fetch(c.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=me(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function gb(e={}){let t=bu(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>vu(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await _i(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:bi(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Ab(e){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await xu(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Su=40;function Sb(e,t,r=Su){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>me(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function Fb(e,t){let r=t?.trim().toLowerCase();return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>me(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function Kb(e,t=24){let r=e?.trim()||void 0;return reactQuery.queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:c,posts:p})=>({tag:c,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function Hb(e,t){let r=t?.trim().toLowerCase();return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>me(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function Lb(e){return reactQuery.queryOptions({queryKey:u.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=exports.ConfigManager.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function Jb(e,t=true){return reactQuery.queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>di(e)})}function Iu(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Pi(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function iv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Pi(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(si(m.author,m.permlink));Iu(y)&&l.push(y);}let[f]=a;return {lastDate:f?Pi(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function cv(e,t,r=true){return reactQuery.queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Tt(e,t)})}function gv(e,t="HIVE",r=200){return reactQuery.infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await ee("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function bv(e,t="HIVE",r="yearly"){return reactQuery.queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ee("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Ov(){return reactQuery.queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function xv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Rv(e,t,r){let n=reactQuery.useQueryClient(),{data:i}=reactQuery.useQuery(M(e));return v(["accounts","update"],e,o=>{let s=Zn(n.getQueryData(M(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ei({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=lr({existingProfile:Xn(a),profile:s.profile,tokens:s.tokens}),c}),await S(t?.adapter,r,[u.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...M(e),staleTime:0});}catch{}}})}function Kv(e,t,r,n,i){return reactQuery.useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=ri(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await Ln(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(u.accounts.relations(e,t),o),t&&b().invalidateQueries(M(t));}})}function mr(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Ie(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function De(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function gr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function yr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Ke(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Uu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Ke(e,o.trim(),r,n))}function Vu(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function Le(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function Be(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function Oi(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function it(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Be(e,t,r,n,i),Oi(e,i)]}function ot(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function st(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function at(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function ut(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function ct(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function hr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Me(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function wr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function _r(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function br(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function Rt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function ju(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Lu(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return Rt(e,t)}function vr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function Ar(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function Pr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Or(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function xr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function $u(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function Wu(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function Er(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Sr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function kr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Cr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Tr(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Rr(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function Gu(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function zu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var xi=(r=>(r.Buy="buy",r.Sell="sell",r))(xi||{}),Ei=(r=>(r.EMPTY="",r.SWAP="9",r))(Ei||{});function qt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function Ft(e,t=3){return e.toFixed(t)}function Ju(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Ft(t,3)} HBD`:`${Ft(t,3)} HIVE`,p=n==="buy"?`${Ft(r,3)} HIVE`:`${Ft(r,3)} HBD`;return qt(e,c,p,false,s,a)}function Fr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function qr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function Yu(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function Xu(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Ir(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Dr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Kr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Br(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let c={...t,account_auths:a};return c.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:c,memo_key:i,json_metadata:o}]}function Zu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function ec(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function tc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function rc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Mr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Nr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function Qr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function $e(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function nc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>$e(e,o.trim(),r,n))}function Hr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function ic(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function oc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function nA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[br(e,n)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function aA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Rt(e,n)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function lA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function gA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function _A(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:n})}function OA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await w()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:c})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(c);o.setQueryData(c,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(E=>({...E,data:E.data.filter(O=>O.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);s?.previousCheck!==void 0&&a.setQueryData(u.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function dc(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Si(e,t){let{data:r}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let c=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=dc(y,n.map((h,E)=>[h[p].createPublic().toString(),E+1])),l};return Z([["account_update",{account:e,json_metadata:r.json_metadata,owner:c("owner"),active:c("active"),posting:c("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function IA(e,t){let{data:r}=reactQuery.useQuery(M(e)),{mutateAsync:n}=Si(e);return reactQuery.useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,i,"owner"),active:H.fromLogin(e,i,"active"),posting:H.fromLogin(e,i,"posting"),memo_key:H.fromLogin(e,i,"memo")}]})},...t})}function QA(e,t,r){let n=reactQuery.useQueryClient(),{data:i}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(i.posting));c.account_auths=c.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:c,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return Z([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),jn__default.default.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(M(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function WA(e,t,r,n){let{data:i}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:c})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await w()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Z([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),jn__default.default.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function zA(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function ki(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function tP(e,t){let{data:r}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=ki(r,o);return Z([["account_update",s]],n)},...t})}function oP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Kr(n,i)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function cP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Br(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function fP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Dr(e,n.newAccountName,n.keys):Ir(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var Ur=300*60*24,Oc=1e4,xc=5e7;function Ci(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,i=C(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Ec(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Sc(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function kc(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=Ci(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Oc/(n*Ur)),a=ur(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-xc,0)}function Cc(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Sc(t))return kc(e,t,n);let i=0;try{if(i=Ci(e),!Number.isFinite(i))return 0}catch{return 0}return Ec(i,r,n)}function hP(e){return ur(e).percentage/100}function wP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*Ur/1e4}function _P(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/Ur;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function bP(e){return xt(e).percentage/100}function vP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let c=Cc(e,t,r,n);return Number.isFinite(c)?c/i*o*(s/a):0}var Tc={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Rc(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Fc(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function qc(e){let t=e[0];return t==="custom_json"?Rc(e):t==="create_proposal"||t==="update_proposal"?Fc(e):Tc[t]??"posting"}function PP(e){let t="posting";for(let r of e){let n=qc(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function kP(e){return reactQuery.useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):Qn(r)?n=H.fromString(r):n=H.from(r),Z([t],n)}})}function RP(e,t,r="active"){return reactQuery.useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function DP(e="/"){return reactQuery.useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>jn__default.default.sendOperation(t,{callback:e},()=>{})})}function NP(){return reactQuery.queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ti(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Ri(e,t){return {...e??{},title:t.title,body:t.body}}function WP(e,t){return reactQuery.useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await w()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Ri(r,n);i.setQueryData(je(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[o,...a.data]}:a)});}})}function e0(e,t){return reactQuery.useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await w()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ti(s,r,n);i.setQueryData(je(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?o(c):c)}))});}})}function s0(e,t){return reactQuery.useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await w()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData(je(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function G(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function c0(e,t,r,n){let o=await w()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await G(o);return {status:o.status,data:s}}async function p0(e){let r=await w()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await G(r);return {status:r.status,data:n}}async function l0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await w()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await G(s);}async function d0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await w()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(s)}async function f0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},c=await w()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function m0(e,t,r){let n={code:e,username:t,token:r},o=await w()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function Fi(e,t){let r={code:e};t&&(r.id=t);let i=await w()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function qi(e,t){let r={code:e,url:t},i=await w()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}var Uc="https://i.ecency.com";async function Ii(e,t,r){let n=w(),i=new FormData;i.append("file",e);let o=await n(`${Uc}/hs/${t}`,{method:"POST",body:i,signal:r});return G(o)}async function g0(e,t,r,n){let i=w(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return G(s)}async function Di(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Ki(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await w()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(a)}async function Bi(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},c=await w()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function Mi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Ni(e,t,r,n,i,o,s,a){let c={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(c.options=o);let l=await w()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function Qi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Hi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function y0(e,t,r){let n={code:e,author:t,permlink:r},o=await w()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function h0(e,t,r){let n={username:e,email:t,friend:r},o=await w()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}function A0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return Ki(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(u.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function S0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Bi(t,i,o,s,a,c)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function q0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return Mi(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let c=o.getQueryData(s);c&&o.setQueryData(s,c.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);n?.(i);}})}function M0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Ni(t,i,o,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function V0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return Qi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function G0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return Hi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)}),o.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function Z0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return qi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function iO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Di(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],c=>c?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},c=>c&&{...c,pages:c.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function uO(e,t){return reactQuery.useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Ii(r,n,i),onSuccess:e,onError:t})}function Dt(e,t){return `/@${e}/${t}`}function Xc(e,t,r){return (r??b()).getQueryData(u.posts.entry(Dt(e,t)))}function Zc(e,t){(t??b()).setQueryData(u.posts.entry(Dt(e.author,e.permlink)),e);}function It(e,t,r,n){let i=n??b(),o=Dt(e,t),s=i.getQueryData(u.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(u.posts.entry(o),a),s}exports.EntriesCacheManagement=void 0;(a=>{function e(c,p,l,f,m){It(c,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(c,p,l,f){It(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){It(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){It(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function i(c,p){c.forEach(l=>Zc(l,p));}a.updateEntries=i;function o(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Dt(c,p))});}a.invalidateEntry=o;function s(c,p,l){return Xc(c,p,l)}a.getEntry=s;})(exports.EntriesCacheManagement||={});function ep(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function tp(e,t,r){let n=exports.EntriesCacheManagement.getEntry(t.author,t.permlink,r);if(!n?.active_votes||ep(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);exports.EntriesCacheManagement.updateVotes(t.author,t.permlink,i,o,r);}function gO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[mr(e,n,i,o)],async(n,i)=>{tp(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function bO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[yr(e,n,i,o??false)],async(n,i)=>{let o=exports.EntriesCacheManagement.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));exports.EntriesCacheManagement.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function OO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(De(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let c=[u.accounts.full(e),u.resourceCredits.account(e)];if(!o){c.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;c.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(c);}},t,"posting",{broadcastMode:r})}function SO(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function Ui(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[c,p]of a)p&&(s.set(c,p),o.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Vi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function kO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(u.posts.entry(o));return s&&i.setQueryData(u.posts.entry(o),{...s,...r}),s}function CO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(u.posts.entry(o),r);}function IO(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[gr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:Ui(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Vi(s);}})}function MO(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;i.push(De(n.author,n.permlink,o,s,a,c,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function UO(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(De(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[u.resourceCredits.account(e)];s.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,c=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===c}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function $O(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[Qr(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var rp=[3e3,3e3,3e3],np=e=>new Promise(t=>setTimeout(t,e));async function ip(e,t){return g("condenser_api.get_content",[e,t])}async function op(e,t,r=0,n){let i=n?.delays??rp,o;try{o=await ip(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await np(s),op(e,t,r+1,n)}var We={};mt(We,{useRecordActivity:()=>Vr});function ap(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Vr(e,t,r){return reactQuery.useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=w(),i=ap(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function rx(e){return reactQuery.queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function ax(e){return reactQuery.queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function lx(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return reactQuery.queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Kt="threespeakfund",hx=1100;function lp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function wx(e,t){if(!lp(t))return e;let r=e.find(n=>n.account===Kt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Kt?{...n,weight:1100}:n):[...e,{account:Kt,weight:1100}]}function _x(e){return e===Kt}var $r={};mt($r,{getAccountTokenQueryOptions:()=>Lr,getAccountVideosQueryOptions:()=>hp});var jr={};mt(jr,{getDecodeMemoQueryOptions:()=>mp});function mp(e,t,r){return reactQuery.queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new jn__default.default.Client({accessToken:r}).decode(t)}})}var ji={queries:jr};function Lr(e,t){return reactQuery.queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await w()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=ji.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function hp(e,t){return reactQuery.queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Lr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await w()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var Kx={queries:$r};function Ux(e){return reactQuery.queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await w()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function $x({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return reactQuery.queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await w()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function Jx(){return reactQuery.queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function eE(e){return reactQuery.queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}var Li={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function nE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Li;let{current_mana:i,max_mana:o}=xt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Li,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,c=s*a,p=i{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function dE(e,t,r,n){let{mutateAsync:i}=Vr(e,"spin-rolled");return reactQuery.useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function yE(e){let t=e?.replace("@","");return reactQuery.queryOptions({queryKey:u.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await w()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var xp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function wE(e,t){return xp.find(r=>r.tier===e&&r.id===t)}var Ep=25;function Sp(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function _E(e){return Sp(e)>Ep}var bE=300,vE=2;function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function Rp(e){let r=await w()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Tp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function xE(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return Rp(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function CE(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Er(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function qE(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Sr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function BE(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[Rr(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function HE(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[kr(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===o.account);return p>=0?c[p]=[c[p][0],o.role,c[p][2]??""]:c.push([o.account,o.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function LE(e,t,r,n){return v(["communities","update",e],t,i=>[Cr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function zE(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Hr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(i.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function ZE(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Tr(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${i.account}/${i.permlink}`),[...u.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function iS(e,t,r=100,n=void 0,i=true){return reactQuery.queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function cS(e,t){return reactQuery.queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function mS(e,t="",r=true){return reactQuery.queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>li(e??"",t)})}var $i=100;async function Wi(e,t){return await g("bridge.list_subscribers",{community:e,limit:$i,...t?{last:t}:{}})??[]}function bS(e){return reactQuery.queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>Wi(e,null),staleTime:6e4})}function vS(e){return reactQuery.infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Wi(e,t),getNextPageParam:t=>t?.length>=$i?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function SS(e,t){return reactQuery.infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function RS(){return reactQuery.queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var Np=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Np||{}),qS={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function DS(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function KS({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function QS(e,t){return reactQuery.queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function jS(e,t,r=void 0){return reactQuery.infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Up=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(Up||{});var Vp=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))(Vp||{}),Gi=[1,2,3,4,5,6,10,13,15,19,20,21,22],jp=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(jp||{});function YS(e,t,r){return reactQuery.queryOptions({queryKey:u.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Gi]})})}function tk(){return reactQuery.queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function ok(e){return reactQuery.queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function zp(e,t){return {...e,read:!t||t===e.id?1:e.read}}function zi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function dk(e,t,r,n){let i=b();return reactQuery.useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Fi(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return zi(f)}});a.forEach(([l,f])=>{if(f&&zi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>zp(h,o)))};i.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=i.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(c,p-1):i.setQueryData(c,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{i.setQueryData(c,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:u.notifications._prefix});}})}function yk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>vr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function bk(e){return reactQuery.queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function Tk(e,t,r){return reactQuery.infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Ct(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function Ik(e){return reactQuery.queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function Mk(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[xr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function Uk(e,t,r){return v(["proposals","create"],e,n=>[Or(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function $k(e,t=50){return reactQuery.infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthee("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function eC(e){return reactQuery.queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function iC(e){return reactQuery.queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function uC(e){return reactQuery.queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function dC(e){return reactQuery.queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function yC(e){return reactQuery.queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function bC(e){return reactQuery.queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function xC(e,t=100){return reactQuery.infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function CC(e){return reactQuery.queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await w()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function qC(e){return reactQuery.queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function BC(e){return reactQuery.queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function le(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function fl(e){if(!e||typeof e!="object")return;let t=e;return {name:le(t.name)??"",symbol:le(t.symbol)??"",layer:le(t.layer)??"hive",balance:ae(t.balance)??0,fiatRate:ae(t.fiatRate)??0,currency:le(t.currency)??"usd",precision:ae(t.precision)??3,address:le(t.address),error:le(t.error),pendingRewards:ae(t.pendingRewards),pendingRewardsFiat:ae(t.pendingRewardsFiat),liquid:ae(t.liquid),liquidFiat:ae(t.liquidFiat),savings:ae(t.savings),savingsFiat:ae(t.savingsFiat),staked:ae(t.staked),stakedFiat:ae(t.stakedFiat),iconUrl:le(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ae(t.apr)}}function ml(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function gl(e){if(!e||typeof e!="object")return;let t=e;return le(t.username)??le(t.name)??le(t.account)}function Ji(e,t="usd",r=true){return reactQuery.queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${exports.ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=ml(o).map(a=>fl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:gl(o)??e,currency:le(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Bt(e){return reactQuery.queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(be().queryKey),r=b().getQueryData(M(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function Yi(e){return reactQuery.queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(M(e).queryKey),r=b().getQueryData(be().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:C(t.hbd_balance).amount+C(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:C(t.hbd_balance).amount},{name:"savings",balance:C(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function _l(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*c*p/f).toFixed(3)}function Xi(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(be().queryKey),r=b().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=C(r.vesting_shares).amount,a=C(r.delegated_vesting_shares).amount,c=C(r.received_vesting_shares).amount,p=C(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=zn(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ue(s,t.hivePerMVests).toFixed(3),y=+Ue(a,t.hivePerMVests).toFixed(3),h=+Ue(c,t.hivePerMVests).toFixed(3),E=+Ue(l,t.hivePerMVests).toFixed(3),O=+Ue(f,t.hivePerMVests).toFixed(3),A=Math.max(m-E,0),P=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+A.toFixed(3),apr:_l(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+P.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...E>0?[{name:"pending_power_down",balance:+E.toFixed(3)}]:[],...O>0&&O!==E?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var K=re.operations,Wr={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay],"":[]};var uT=Object.keys(re.operations);var Zi=re.operations,lT=Zi,dT=Object.entries(Zi).reduce((e,[t,r])=>(e[r]=t,e),{});var eo=re.operations;function vl(e){return Object.prototype.hasOwnProperty.call(eo,e)}function pt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in Wr){Wr[a].forEach(c=>o.add(c));return}vl(a)&&o.add(eo[a]);});let s=Ol(Array.from(o));return {filterKey:i,filterArgs:s}}function Gr(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Al(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Pl(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Ol(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,Pl(Number(s),t),...n])).map(c=>({num:c[0],type:c[1].op[0],timestamp:c[1].timestamp,trx_id:c[1].trx_id,...c[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return C(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=C(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return C(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function PT(e,t=20,r=[]){let{filterKey:n}=pt(r),i=Gr(r);return reactQuery.infiniteQueryOptions({...Mt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return C(c.hbd_payout).amount>0;case "claim_reward_balance":return C(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return C(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=C(c.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(c.type)}}))})})}function kT(e,t=20,r=[]){let{filterKey:n}=pt(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return reactQuery.infiniteQueryOptions({...Mt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.vesting_payout).amount>0;case "claim_reward_balance":return C(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(C(p.amount).symbol);case "fill_recurrent_transfer":let m=C(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function to(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function zr(e,t){return new Date(e.getTime()-t*1e3)}function FT(e=86400){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,to(t),to(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[zr(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[zr(n,Math.max(100*e,28800)),zr(n,e)]})}function KT(e){return reactQuery.queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function QT(e,t=50){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function LT(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>C(n.vesting_shares).amount-C(r.vesting_shares).amount)})}function zT(e=500){return reactQuery.queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function ZT(){return reactQuery.queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function nR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return reactQuery.queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function aR(){return reactQuery.queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function lR(e,t,r,n){return reactQuery.queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=w(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ro(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function gR(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return reactQuery.queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[ro(i),ro(n),e])})}function _R(){return reactQuery.queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function PR(){return reactQuery.queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function SR(e,t,r){return v(["market","limit-order-create"],e,n=>[qt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function RR(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Fr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function lt(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function IR(e,t,r,n){let i=w(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return lt(s)}async function no(e){if(e==="hbd")return 1;let t=w(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await lt(n)).hive_dollar[e]}async function DR(e,t){let n=await w()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return lt(n)}async function KR(){let t=await w()(d.privateApiHost+"/private-api/market-data/latest");return lt(t)}async function BR(){let t=await w()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return lt(t)}var Nl={"Content-type":"application/json"};async function Ql(e){let t=w(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Nl});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function xe(e,t){try{return await Ql(e)}catch{return t}}async function QR(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([xe({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),xe({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((c,p)=>{let l=Number(c.price??0);return Number(p.price??0)-l}),s=a=>a.sort((c,p)=>{let l=Number(c.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function HR(e,t=50){return xe({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function UR(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([xe({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),xe({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),c=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...c].sort((p,l)=>l.timestamp-p.timestamp)}async function Hl(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return xe({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Ge(e,t){return Hl(t,e)}async function Nt(e){return xe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Qt(e){return xe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function io(e,t,r,n){let i=w(),o=exports.ConfigManager.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function oo(e,t="daily"){let r=w(),n=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function so(e){let t=w(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function Ht(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Nt(e)})}function zR(){return reactQuery.queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ge()})}function ao(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Qt(e)})}function rF(e,t,r=20){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return io(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function sF(e,t="daily"){return reactQuery.queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>oo(e,t)})}function pF(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await so(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function uo(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ge(e,t)})}function ze(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,c=typeof a=="string"?parseFloat(a):a;return s+=c.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var Ut=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${ze(this.stake,{fractionDigits:this.precision})} + ${ze(this.delegationsIn,{fractionDigits:this.precision})} - ${ze(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():ze(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():ze(this.balance,{fractionDigits:this.precision})};function vF(e,t,r){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await Nt(e),i=await Qt(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),c=[...s,...a.length?await Ge(void 0,a):[]];return n.map(p=>{let l=i.find(O=>O.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=c.find(O=>O.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),E=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new Ut({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:E})})},enabled:!!e})}function co(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Bt(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(ao([t])),s=await r.ensureQueryData(Ht(e)),a=await r.ensureQueryData(uo(void 0,t)),c=o?.find(O=>O.symbol===t),p=s?.find(O=>O.symbol===t),f=+(a?.find(O=>O.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),E=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&E.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:E}}})}function dt(e,t=0){return reactQuery.queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function po(e){return reactQuery.queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(dt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(dt(e).queryKey)?.points??0)})})}function NF(e,t){return reactQuery.queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function YF(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await no(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=Ji(e,i,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let O=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let A=Math.abs(Number.parseFloat(O[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:A}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:A}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:A});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return reactQuery.queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Bt(e));else if(t==="HP")l=await o(Xi(e));else if(t==="HBD")l=await o(Yi(e));else if(t==="POINTS")l=await o(po(e));else if((await n.ensureQueryData(Ht(e))).some(m=>m.symbol===t))l=await o(co(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var td=(A=>(A.Transfer="transfer",A.TransferToSavings="transfer-saving",A.WithdrawFromSavings="withdraw-saving",A.Delegate="delegate",A.PowerUp="power-up",A.PowerDown="power-down",A.WithdrawRoutes="withdraw-routes",A.ClaimInterest="claim-interest",A.Swap="swap",A.Convert="convert",A.Gift="gift",A.Promote="promote",A.Claim="claim",A.Buy="buy",A.Stake="stake",A.Unstake="unstake",A.Undelegate="undelegate",A))(td||{});function nq(e,t,r){return v(["wallet","transfer"],e,n=>[Ke(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function uq(e,t,r){return v(["wallet","transfer-point"],e,n=>[$e(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function fq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[at(e,n.delegatee,n.vestingShares)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[ut(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await S(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function Aq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Sq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Le(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Fq(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Be(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Bq(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[ot(e,n.to,n.amount)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Uq(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[st(e,n.vestingShares)],async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Wq(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?hr(e,n.amount,n.requestId):ct(e,n.amount,n.requestId)],async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Xq(e,t,r){return v(["wallet","claim-interest"],e,n=>it(e,n.to,n.amount,n.memo,n.requestId),async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var rd=5e3,Vt=new Map;function nI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[qr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],u.assets.hiveGeneralInfo(e),u.assets.hbdGeneralInfo(e),u.assets.hivePowerGeneralInfo(e)],o=Vt.get(n);o&&(clearTimeout(o),Vt.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Vt.delete(n);}},rd);Vt.set(n,s);},t,"posting",{broadcastMode:r})}function aI(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function lI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _I(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PI(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function SI(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nd(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Ke(n,i,o,s)];case "transfer-saving":return [Le(n,i,o,s)];case "withdraw-saving":return [Be(n,i,o,s,a)];case "power-up":return [ot(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Ke(n,i,o,s)];case "transfer-saving":return [Le(n,i,o,s)];case "withdraw-saving":return [Be(n,i,o,s,a)];case "claim-interest":return it(n,i,o,s,a);case "convert":return [ct(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [st(n,o)];case "delegate":return [at(n,i,o)];case "withdraw-routes":return [ut(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [$e(n,i,o,s)];break}return null}function id(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [Me(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [Me(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [Me(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [Me(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [Me(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [wr(n,[e])]}return null}function od(e){return e==="claim"?"posting":"active"}function qI(e,t,r,n,i){let{mutateAsync:o}=We.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=nd(t,r,s);if(a)return a;let c=id(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,od(r),{broadcastMode:i})}function BI(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[_r(e,n,i)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),u.resourceCredits.account(e),u.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function HI(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[Ar(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function LI(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Pr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function ad(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function YI(e){return reactQuery.infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ee("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(ad),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function XI(e,t,r,n="vests",i="desc"){return reactQuery.queryOptions({queryKey:u.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await ee("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function ZI(e){return reactQuery.queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await ee("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var ud=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(ud||{});async function pd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await w()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function sD(e,t,r,n){let{mutateAsync:i}=We.useRecordActivity(e,"points-claimed");return reactQuery.useMutation({mutationFn:()=>pd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(dt(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var fo=/(^|\s)author:([^\s]+)/g,mo=/(^|\s)type:([^\s]+)/g,go=/(^|\s)category:([^\s]+)/g,yo=/(^|\s)tag:([^\s]+)/g;var wo=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(wo||{}),uD=5,cD=100;function _o(e){return e.trim().split(/\s+/)[0]??""}function ld(e){return _o(e).replace(/^@+/,"").toLowerCase()}function dd(e){return _o(e).replace(/^#+/,"").toLowerCase()}function fd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function pD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=ld(t),a=dd(n),c=fd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),c.length>0&&p.push(`tag:${c.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:c}}var ho=class{query="";search="";author="";type="";category="";tags=[];constructor(t){this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}grab=t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""};grabAuthor=()=>{this.author=this.grab(fo);};grabType=()=>{let t=this.grab(mo);Object.values(wo).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(go);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(yo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([fo,mo,go,yo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();}};async function ve(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Ee(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var gd=reactQuery.isServer?0:3;function ft(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let c=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(_e,s)});return ve(c,Ee)},retry:ft})}function vD(e,t,r=true){return reactQuery.infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:c,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:we(_e,i)});return ve(y,Ee)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:ft})}async function xD(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await w()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(_e,s)});return ve(p,Ee)}async function bo(e,t,r=_e){let i=await w()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:we(r,t)});return ve(i,Ee)}async function ED(e,t){let n=await w()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:we(_e,t)}),i=await ve(n,Array.isArray);return i?.length>0?i:[e]}var _d=4368*60*60*1e3,bd=4,vd=3e3,Ad=2e3,Pd=4e3,RD=2;function Od(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function xd(e){let t=5381;for(let r=0;r>>0).toString(36)}function FD(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Od(e.body??"",vd),o=xd(`${t}|${n.join(",")}|${i}`);return reactQuery.queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-_d).toISOString().slice(0,19),c=await bo({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?Ad:Pd),p=[],l=new Set;for(let f of c.results){if(p.length>=bd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function MD(e,t=5){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Tt(n)},enabled:!!r})}function VD(e,t=10){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function zD(e,t,r,n,i,o){return reactQuery.infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),i!==void 0&&(c.votes=i),o&&(c.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(c),signal:we(_e,a)});return ve(p,Ee)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:ft})}function ZD(e){return reactQuery.queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function Rd(e){let r=await w()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function nK(e,t){let r=e?.replace("@","");return reactQuery.queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Rd(t)},enabled:!!r&&!!t})}async function Id(e,t){let n=await w()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Dd(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function uK(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Id(t,i)},onSuccess(i){n&&Dd(r,n,i);}})}function dK(e){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function yK(e){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function bK(e,t){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function OK(e){return reactQuery.queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function kK(e,t){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function FK(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[Mr(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function KK(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Nr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function NK(e){let r=await w()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var Ud="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function VK(){return reactQuery.queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Ud,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` -`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var LK=1.1,Vd=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Vd||{});function $K(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function $d(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let c=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:c?{total_votes:c.total_votes??0,hive_hp:c.hive_hp,hive_proxied_hp:c.hive_proxied_hp,hive_hp_incl_proxied:c.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function YK(e,t){return reactQuery.queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:reactQuery.isServer?$n:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=w(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return $d(o[0])}})}function eB(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** +'use strict';var reactQuery=require('@tanstack/react-query'),utils_js=require('@noble/hashes/utils.js'),legacy_js=require('@noble/hashes/legacy.js'),an=require('bs58'),secp256k1_js=require('@noble/curves/secp256k1.js'),sha2_js=require('@noble/hashes/sha2.js'),aes_js=require('@noble/ciphers/aes.js'),Gn=require('hivesigner');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var an__default=/*#__PURE__*/_interopDefault(an);var Gn__default=/*#__PURE__*/_interopDefault(Gn);var So=Object.defineProperty;var ht=(e,t)=>{for(var r in t)So(e,r,{get:t[r],enumerable:true});};var _t=new ArrayBuffer(0),wt=null,bt=null;function ko(){return wt||(typeof TextEncoder<"u"?wt=new TextEncoder:wt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),wt}function en(){return bt||(typeof TextDecoder<"u"?bt=new TextDecoder:bt={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),bt}var I=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?_t:new ArrayBuffer(t),this.view=t===0?new DataView(_t):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(_t));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof e?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,i=new e(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?_t:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=ko().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=en().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=en().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};var E={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},zt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Jt=e=>{let t=zt(e);t.length&&(E.nodes=t);},Yt=e=>{let t=zt(e);t.length&&(E.restNodes=t);},Xt=e=>{if(!e||typeof e!="object")return;let t={...E.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=zt(n);i.length?t[r]=i:delete t[r];}E.restNodesByApi=t;},Zt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(E.userAgent=t);},er=e=>{if(!e||typeof e!="object")return;let t=E.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var Pe=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=utils_js.hexToBytes(t),n=parseInt(utils_js.bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return utils_js.bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=utils_js.hexToBytes(t));let r=secp256k1_js.secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1_js.secp256k1.Signature(r.r,r.s,this.recovery);return new J(n.recoverPublicKey(t).toBytes())}};var J=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??E.address_prefix;}static fromString(t){let r=E.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=an__default.default.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=legacy_js.ripemd160(o).subarray(0,4);if(!To(s,a))throw new Error("Public key checksum mismatch");try{secp256k1_js.secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Pe.from(r)),secp256k1_js.secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Co(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Co=(e,t)=>{let r=legacy_js.ripemd160(e);return t+an__default.default.encode(new Uint8Array([...e,...r.subarray(0,4)]))},To=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},w=(e,t)=>{e.writeVString(t);},qo=(e,t)=>{e.writeInt16(t);},un=(e,t)=>{e.writeInt64(t);},cn=(e,t)=>{e.writeUint8(t);},ce=(e,t)=>{e.writeUint16(t);},Y=(e,t)=>{e.writeUint32(t);},pn=(e,t)=>{e.writeUint64(t);},ye=(e,t)=>{e.writeByte(t?1:0);},ln=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},q=(e,t)=>{let r=vt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},Oe=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},fe=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(J.from(t).key);},dn=(e=null)=>(t,r)=>{r=At.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},fn=dn(),tr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ue=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},Ce=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=ue([["weight_threshold",Y],["account_auths",tr(w,ce)],["key_auths",tr(fe,ce)]]),Io=ue([["account",w],["weight",ce]]),rr=ue([["base",q],["quote",q]]),Do=ue([["account_creation_fee",q],["maximum_block_size",Y],["hbd_interest_rate",ce]]),R=(e,t)=>{let r=ue(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},k={};k.account_create=R(T.account_create,[["fee",q],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w]]);k.account_create_with_delegation=R(T.account_create_with_delegation,[["fee",q],["delegation",q],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w],["extensions",V(ie)]]);k.account_update=R(T.account_update,[["account",w],["owner",Ce(W)],["active",Ce(W)],["posting",Ce(W)],["memo_key",fe],["json_metadata",w]]);k.account_witness_proxy=R(T.account_witness_proxy,[["account",w],["proxy",w]]);k.account_witness_vote=R(T.account_witness_vote,[["account",w],["witness",w],["approve",ye]]);k.cancel_transfer_from_savings=R(T.cancel_transfer_from_savings,[["from",w],["request_id",Y]]);k.change_recovery_account=R(T.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",V(ie)]]);k.claim_account=R(T.claim_account,[["creator",w],["fee",q],["extensions",V(ie)]]);k.claim_reward_balance=R(T.claim_reward_balance,[["account",w],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);k.comment=R(T.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);k.comment_options=R(T.comment_options,[["author",w],["permlink",w],["max_accepted_payout",q],["percent_hbd",ce],["allow_votes",ye],["allow_curation_rewards",ye],["extensions",V(ln([ue([["beneficiaries",V(Io)]])]))]]);k.convert=R(T.convert,[["owner",w],["requestid",Y],["amount",q]]);k.create_claimed_account=R(T.create_claimed_account,[["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w],["extensions",V(ie)]]);k.custom=R(T.custom,[["required_auths",V(w)],["id",ce],["data",fn]]);k.custom_json=R(T.custom_json,[["required_auths",V(w)],["required_posting_auths",V(w)],["id",w],["json",w]]);k.decline_voting_rights=R(T.decline_voting_rights,[["account",w],["decline",ye]]);k.delegate_vesting_shares=R(T.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",q]]);k.delete_comment=R(T.delete_comment,[["author",w],["permlink",w]]);k.escrow_approve=R(T.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Y],["approve",ye]]);k.escrow_dispute=R(T.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Y]]);k.escrow_release=R(T.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",Y],["hbd_amount",q],["hive_amount",q]]);k.escrow_transfer=R(T.escrow_transfer,[["from",w],["to",w],["hbd_amount",q],["hive_amount",q],["escrow_id",Y],["agent",w],["fee",q],["json_meta",w],["ratification_deadline",Oe],["escrow_expiration",Oe]]);k.feed_publish=R(T.feed_publish,[["publisher",w],["exchange_rate",rr]]);k.limit_order_cancel=R(T.limit_order_cancel,[["owner",w],["orderid",Y]]);k.limit_order_create=R(T.limit_order_create,[["owner",w],["orderid",Y],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",ye],["expiration",Oe]]);k.limit_order_create2=R(T.limit_order_create2,[["owner",w],["orderid",Y],["amount_to_sell",q],["exchange_rate",rr],["fill_or_kill",ye],["expiration",Oe]]);k.recover_account=R(T.recover_account,[["account_to_recover",w],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);k.request_account_recovery=R(T.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",W],["extensions",V(ie)]]);k.reset_account=R(T.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",W]]);k.set_reset_account=R(T.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);k.set_withdraw_vesting_route=R(T.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",ce],["auto_vest",ye]]);k.transfer=R(T.transfer,[["from",w],["to",w],["amount",q],["memo",w]]);k.transfer_from_savings=R(T.transfer_from_savings,[["from",w],["request_id",Y],["to",w],["amount",q],["memo",w]]);k.transfer_to_savings=R(T.transfer_to_savings,[["from",w],["to",w],["amount",q],["memo",w]]);k.transfer_to_vesting=R(T.transfer_to_vesting,[["from",w],["to",w],["amount",q]]);k.vote=R(T.vote,[["voter",w],["author",w],["permlink",w],["weight",qo]]);k.withdraw_vesting=R(T.withdraw_vesting,[["account",w],["vesting_shares",q]]);k.witness_update=R(T.witness_update,[["owner",w],["url",w],["block_signing_key",fe],["props",Do],["fee",q]]);k.witness_set_properties=R(T.witness_set_properties,[["owner",w],["props",tr(w,fn)],["extensions",V(ie)]]);k.account_update2=R(T.account_update2,[["account",w],["owner",Ce(W)],["active",Ce(W)],["posting",Ce(W)],["memo_key",Ce(fe)],["json_metadata",w],["posting_json_metadata",w],["extensions",V(ie)]]);k.create_proposal=R(T.create_proposal,[["creator",w],["receiver",w],["start_date",Oe],["end_date",Oe],["daily_pay",q],["subject",w],["permlink",w],["extensions",V(ie)]]);k.update_proposal_votes=R(T.update_proposal_votes,[["voter",w],["proposal_ids",V(un)],["approve",ye],["extensions",V(ie)]]);k.remove_proposal=R(T.remove_proposal,[["proposal_owner",w],["proposal_ids",V(un)],["extensions",V(ie)]]);var Ko=ue([["end_date",Oe]]);k.update_proposal=R(T.update_proposal,[["proposal_id",pn],["creator",w],["daily_pay",q],["subject",w],["permlink",w],["extensions",V(ln([ie,Ko]))]]);k.collateralized_convert=R(T.collateralized_convert,[["owner",w],["requestid",Y],["amount",q]]);k.recurrent_transfer=R(T.recurrent_transfer,[["from",w],["to",w],["amount",q],["memo",w],["recurrence",ce],["executions",ce],["extensions",V(ue([["type",cn],["value",ue([["pair_id",cn]])]]))]]);var Bo=(e,t)=>{let r=k[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},No=ue([["ref_block_num",ce],["ref_block_prefix",Y],["expiration",Oe],["operations",V(Bo)],["extensions",V(w)]]),Mo=ue([["from",fe],["to",fe],["nonce",pn],["check",Y],["encrypted",dn()]]),pe={Asset:q,Memo:Mo,Price:rr,PublicKey:fe,String:w,Transaction:No,UInt16:ce,UInt32:Y};var tt=e=>new Promise(t=>setTimeout(t,e));var Qo=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function hn(){return Qo?{"User-Agent":E.userAgent}:{}}var X=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},Te=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function _n(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Ho=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Uo=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Vo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function jo(e){if(!e)return false;if(e instanceof Te)return true;if(e instanceof X)return false;let t=Vo(e);return !!(Ho.some(r=>t.includes(r))||Uo.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function nr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function wn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Lo=1e4,$o=6e4,Wo=12e4,mn=2,gn=6e4,yn=12e4,Go=30,rt=.3,ir=3,nt=5*6e4,bn=6e4,vn=1e3,An=2e3,Ot=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=ir&&i-o.updatedAt<=nt?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>nt&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:rt*r+(1-rt)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>nt?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=rt*r+(1-rt)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=mn&&(o.cooldownUntil=i+gn),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,mn),o.lastFailureTime=i,o.cooldownUntil=i+gn,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>Wo&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(Lo*2**n.rateLimitStreak,$o);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=yn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=yn&&o-n.headBlock>Go)}getOrderedNodes(t,r){let n=[],i=[];for(let u of t)this.isNodeHealthy(u,r)?n.push(u):i.push(u);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((u,p)=>({node:u,i:p,score:this.scoreNode(u,o)})).sort((u,p)=>u.score-p.score||u.i-p.i).map(u=>u.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(u=>u!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=ir&&r-t.latencyUpdatedAt<=nt}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:vn}pickReprobeCandidate(t,r){let n=r-bn,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),u=Math.max(a.latencyUpdatedAt,a.lastProbeAt);u<=n&&u=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(E.resilience.hedgeBucketCapacity,this.tokens+E.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>E.resilience.hedgeBucketCapacity&&(this.tokens=E.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=E.resilience.hedgeBucketCapacity){this.tokens=t;}},sr=new or;function xt(e,t,r,n,i){let o=E.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function ar(e,t,r,n){r instanceof Te?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof X?e.recordFailure(t,n):e.recordFailure(t);}function Pn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function zo(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function On(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(zo()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function cr(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var it=async(e,t,r,n=E.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:u,cleanup:p}=On(n),{signal:l,cleanup:f}=cr(u,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...hn()},signal:l});if(y.status===429)throw new Te(e,"HTTP 429 Rate Limited",{rateLimitMs:_n(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new Te(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let O=h.error;throw "message"in O&&"code"in O?new X(O):h.error}throw h}catch(y){if(y instanceof X||y instanceof Te||o?.aborted)throw y;if(i)return it(e,t,r,n,false,o);throw y}finally{m();}};function Pt(){return tt(50+Math.random()*50)}function Jo(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:u,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,O=0,x=false,A=false,P,L,U=0,B=[],Q=z=>{if(!h){h=true,L!==void 0&&(clearTimeout(L),L=void 0);for(let F of B)F.signal.aborted||F.abort();z();}},$=(z,F)=>{O++;let de=new AbortController;B.push(de);let et=cr(de.signal,p),Eo=xt(j,z,t,s,a),Gt=Date.now();F||(U=Gt),it(z,t,r,Eo,false,et.signal).then(ne=>{if(et.cleanup(),O--,F||(A=true),!h){if(f&&!f(ne)){if(j.recordDefectiveResponse(z,n),P=new Error(`[hive-tx] response validation failed for ${t} from ${z}`),!F&&!x){Q(()=>y(P));return}O===0&&Q(()=>y(P));return}j.recordSuccess(z,n,Date.now()-Gt,t),Pn(j,z,t,ne),F?A||j.recordCensoredLatency(i,Date.now()-U,t):x||sr.refill(),Q(()=>m(ne));}}).catch(ne=>{if(et.cleanup(),O--,F||(A=true),!h){if(p?.aborted){Q(()=>y(ne));return}if(ne instanceof X&&!nr(ne.code,ne.message)){Q(()=>y(ne));return}if(ar(j,z,ne,n),j.recordSlowFailure(z,Date.now()-Gt,t),P=ne,!F&&!x){Q(()=>y(ne));return}O===0&&Q(()=>y(P));}});};$(i,false);let ke=j.getUsableLatencyMs(i,t)??0,Ze=xt(j,i,t,s,a),Wt=Math.min(Math.max(E.resilience.hedgeDelayFloorMs,E.resilience.hedgeDelayFactor*ke),.8*Ze);L=setTimeout(()=>{if(L=void 0,h||p?.aborted||Date.now()>=u)return;let z=o.filter(de=>j.isNodeHealthy(de,n));if(z.length===0)return;let F=z[Math.floor(Math.random()*z.length)];sr.trySpend()&&(x=true,l(F),$(F,true));},Wt);})}var g=async(e,t=[],r,n=E.retry,i,o)=>{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??E.timeout,u=wn(e),p=Date.now()+E.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=j.getOrderedNodes(E.nodes,u),h=y.find(A=>!l.has(A));h||(l.clear(),h=y[0]),l.add(h);let O=[];if(E.resilience.hedge&&j.getUsableLatencyMs(h,e)!==void 0&&(O=y.filter(A=>!l.has(A)&&j.isNodeHealthy(A,u)).slice(0,3)),O.length>0)try{return await Jo({method:e,params:t,api:u,primary:h,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:A=>l.add(A),validate:o})}catch(A){if(A instanceof X&&!nr(A.code,A.message)||i?.aborted)throw A;f=A,m{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let i=wn(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await it(p,e,t,r,!1,n);return j.recordSuccess(p,i),l}catch(l){if(l instanceof X||n?.aborted||(ar(j,p,l,i),s=l,!jo(l)))throw l}}throw s},Yo={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function ee(e,t,r,n,i=E.retry,o){if(!Array.isArray(E.restNodes))throw new Error("config.restNodes is not an array");if(E.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??E.timeout,u=Date.now()+E.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=E.restNodesByApi?.[e]?.length?E.restNodesByApi[e]:E.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=u);h++){let O=xe.getOrderedNodes(l,e),x=O.find(F=>!f.has(F));x||(f.clear(),x=O[0]),f.add(x);let A=x+Yo[e],P=t,L=r||{},U=new Set;Object.entries(L).forEach(([F,de])=>{P.includes(`{${F}}`)&&(P=P.replace(`{${F}}`,encodeURIComponent(String(de))),U.add(F));});let B=new URL(A+P);if(Object.entries(L).forEach(([F,de])=>{U.has(F)||(Array.isArray(de)?de.forEach(et=>B.searchParams.append(F,String(et))):B.searchParams.set(F,String(de)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:Q,cleanup:$}=On(xt(xe,x,p,a,s)),{signal:ke,cleanup:Ze}=cr(Q,o),Wt=()=>{$(),Ze();},z=Date.now();try{let F=await fetch(B.toString(),{signal:ke,headers:hn()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw xe.recordRateLimit(x,_n(F.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${x}`);if(F.status===503)throw xe.recordFailure(x,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${x}`);if(!F.ok)throw xe.recordFailure(x,e),y=!0,new Error(`HTTP ${F.status} from ${x}`);return xe.recordSuccess(x,e,Date.now()-z,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||o?.aborted)throw F;y||xe.recordFailure(x,e),xe.recordSlowFailure(x,Date.now()-z,p),m=F,h{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an Array");if(r>E.nodes.length)throw new Error("quorum > config.nodes.length");let o=(u=>{let p=[...u];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(E.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let u=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Xo(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Xo(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var es=utils_js.hexToBytes(E.chain_id),Re=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await He("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof X&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await tt(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=utils_js.hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};}};var Tn=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1_js.secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(is(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=utils_js.hexToBytes(t);else {let n=[];for(let i=0;i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha2_js.sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1_js.secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(utils_js.bytesToHex(r.subarray(0,1)),16);return Pe.from((n+31).toString(16)+utils_js.bytesToHex(r.subarray(1)))}createPublic(t){return new J(secp256k1_js.secp256k1.getPublicKey(this.key),t)}toString(){return ns(new Uint8Array([...Tn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1_js.secp256k1.getSharedSecret(this.key,t.key);return sha2_js.sha512(r.subarray(1))}static randomKey(){return new e(secp256k1_js.secp256k1.keygen().secretKey)}},Rn=e=>sha2_js.sha256(sha2_js.sha256(e)),ns=e=>{let t=Rn(e);return an__default.default.encode(new Uint8Array([...e,...t.slice(0,4)]))},is=e=>{let t=an__default.default.decode(e);if(!kn(t.slice(0,1),Tn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=Rn(n).slice(0,4);if(!kn(r,i))throw new Error("Private key checksum mismatch");return n},kn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nDn(e,t,n,r),In=(e,t,r,n,i)=>Dn(e,t,r,n,i).message,Dn=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let u=sha2_js.sha512(new Uint8Array(a.toBuffer())),p=u.subarray(32,48),l=u.subarray(0,32),f=sha2_js.sha256(u).subarray(0,4),m=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=cs(n,l,p);}else n=us(n,l,p);return {nonce:o,message:n,checksum:y}},cs=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).decrypt(n),n},us=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).encrypt(n),n},pr=null,ps=()=>{if(pr===null){let r=secp256k1_js.secp256k1.utils.randomSecretKey();pr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++pr%65536;return e=e<{let t=ys(e,33);return new J(t)},ds=e=>e.readUint64(),fs=e=>e.readUint32(),ms=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},gs=e=>t=>{let r={},n=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function ys(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var hs=gs([["from",Kn],["to",Kn],["nonce",ds],["check",fs],["encrypted",ms]]),Bn={Memo:hs};var Mn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Hn(),e=Un(e),t=_s(t);let i=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:u}=qn(e,t,o,n),p=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);pe.Memo(p,{check:u,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+an__default.default.encode(l)},Qn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Hn(),e=Un(e);let r=Bn.Memo(an__default.default.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new J(n.key).toString()?new J(i.key):new J(n.key);r=In(e,p,o,a,s);let l=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},St,Hn=()=>{if(St===void 0){let e;St=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Mn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Qn(t,n);}finally{St=e==="#memo\u7231";}}if(St===false)throw new Error("This environment does not support encryption.")},Un=e=>typeof e=="string"?H.fromString(e):e,_s=e=>typeof e=="string"?J.fromString(e):e,Vn={decode:Qn,encode:Mn};var re={};ht(re,{buildWitnessSetProperties:()=>Os,makeBitMaskFilter:()=>As,operations:()=>vs,validateUsername:()=>bs});var bs=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(Ps,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),Ps=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=pe.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=pe.UInt32;break;case "hbd_interest_rate":i=pe.UInt16;break;case "url":i=pe.String;break;case "hbd_exchange_rate":i=pe.Price;break;case "account_creation_fee":i=pe.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,xs(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},xs=(e,t)=>{let r=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return e(r,t),r.flip(),utils_js.bytesToHex(new Uint8Array(r.toBuffer()))};function Pm(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha2_js.sha256(t)}function jn(e){try{return H.fromString(e),!0}catch{return false}}async function Z(e,t){let r=new Re;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),He("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Ln(e,t){let r=new Re;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var Ss=432e3;function $n(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/Ss,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function ks(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function lr(e){let t=ks(e)*1e6;return $n(t,e.voting_manabar)}function kt(e){return $n(Number(e.max_rc),e.rc_manabar)}var Wn=(u=>(u.COMMON="common",u.INFO="info",u.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",u.MISSING_AUTHORITY="missing_authority",u.TOKEN_EXPIRED="token_expired",u.NETWORK="network",u.TIMEOUT="timeout",u.VALIDATION="validation",u))(Wn||{});function Ue(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Cs(e){let t=Ue(e);return [t.message,t.type]}function he(e){let{type:t}=Ue(e);return t==="missing_authority"||t==="token_expired"}function Ts(e){let{type:t}=Ue(e);return t==="insufficient_resource_credits"}function Rs(e){let{type:t}=Ue(e);return t==="info"}function Fs(e){let{type:t}=Ue(e);return t==="network"||t==="timeout"}async function _e(e,t,r,n,i="posting",o,s,a="async"){let u=n?.adapter;switch(e){case "key":{if(!u)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(u.getOwnerKey)p=await u.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":u.getActiveKey&&(p=await u.getActiveKey(t));break;case "memo":if(u.getMemoKey)p=await u.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await u.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Ln(r,l):await Z(r,l)}case "hiveauth":{if(!u?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await u.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!u)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await u.getAccessToken(t);if(p)try{return (await new Gn__default.default.Client({accessToken:p}).broadcast(r)).result}catch(l){if(u.broadcastWithHiveSigner&&he(l))return await u.broadcastWithHiveSigner(t,r,i);throw l}if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!u?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await u.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Is(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await _e(l,e,t,r,n,void 0,void 0,i)}catch(m){if(he(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(he(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await _e(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let O;switch(n){case "owner":o.getOwnerKey&&(O=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(O=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(O=await o.getMemoKey(e));break;default:O=await o.getPostingKey(e);break}O?y=O:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let O=await o.getAccessToken(e);O&&(h=O);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await _e(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!he(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return reactQuery.useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async u=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(u);try{if(i?.enableFallback!==!1&&i?.adapter)return await Is(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=H.fromString(l);return await Z(p,m)}let f=i?.accessToken;if(f)return (await new Gn__default.default.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof X?new Error(l.message):l}}})}async function zn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let u=H.fromString(o);return Z([["custom_json",i]],u)}let s=n?.accessToken;if(s)return (await new Gn__default.default.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let u=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,u,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,u,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Mm=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function we(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var Fe=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),Bs=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},be=1e4,Jn=120*1e3,Ct,Ns;function Ms(){return Ct?Ct():Ns??=new reactQuery.QueryClient}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return E.nodes},heliusApiKey:Bs(),get queryClient(){return Ms()},set queryClient(e){Ct=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false};exports.ConfigManager=void 0;(A=>{function e(P){d.queryClient=P;}A.setQueryClient=e;function t(P){Ct=P;}A.setQueryClientResolver=t;function r(P){d.privateApiHost=P;}A.setPrivateApiHost=r;function n(P){d.clientId=P;}A.setClientId=n;function i(P){if(typeof P!="string"||P.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=P;}A.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}A.getValidatedBaseUrl=o;function s(P){d.pollsApiHost=P;}A.setPollsApiHost=s;function a(P){d.imageHost=P;}A.setImageHost=a;function u(P){Jt(P);}A.setHiveNodes=u;function p(P){Yt(P);}A.setRestNodes=p;function l(P){Xt(P);}A.setRestNodesByApi=l;function f(P){Zt(P);}A.setUserAgent=f;function m(P){er(P);}A.setResilience=m;function y(P){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(P))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(P))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(P))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(P)||/\.\+\.\+/.test(P))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let L=/\.?\{(\d+),(\d+)\}/g,U;for(;(U=L.exec(P))!==null;){let[,B,Q]=U;if(parseInt(Q,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${Q}}`}}return {safe:true}}function h(P){let L=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],U=5;for(let B of L){let Q=Date.now();try{P.test(B);let $=Date.now()-Q;if($>U)return {safe:!1,reason:`runtime test exceeded ${U}ms (took ${$}ms on input length ${B.length})`}}catch($){return {safe:false,reason:`runtime test threw error: ${$}`}}}return {safe:true}}function O(P,L=200){try{if(!P)return Fe&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(P.length>L)return Fe&&console.warn(`[SDK] DMCA pattern rejected: length ${P.length} exceeds max ${L} - pattern: ${P.substring(0,50)}...`),null;let U=y(P);if(!U.safe)return Fe&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${U.reason}) - pattern: ${P.substring(0,50)}...`),null;let B;try{B=new RegExp(P);}catch($){return Fe&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${P.substring(0,50)}...`,$),null}let Q=h(B);return Q.safe?B:(Fe&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Q.reason}) - pattern: ${P.substring(0,50)}...`),null)}catch(U){return Fe&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${P.substring(0,50)}...`,U),null}}function x(P={}){let L=$=>Array.isArray($)?$.filter(ke=>typeof ke=="string"):[],U=P||{},B={accounts:L(U.accounts),tags:L(U.tags),patterns:L(U.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map($=>O($)).filter($=>$!==null),d.dmcaPatternRegexes=[];let Q=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Fe&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${Q} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),Q>0&&console.warn(`[SDK] ${Q} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}A.setDmcaLists=x;})(exports.ConfigManager||={});function Ym(){return new reactQuery.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient;exports.EcencyQueriesManager=void 0;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>reactQuery.useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>reactQuery.useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(exports.EcencyQueriesManager||={});function Zm(e){return btoa(JSON.stringify(e))}function eg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Yn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Yn||{}),Tt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Tt||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Yn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Tt[e.nai]}}var dr;function _(){if(!dr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");dr=globalThis.fetch.bind(globalThis);}return dr}function Xn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function js(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return js(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ve(e,t){return e/1e6*t}function Zn(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var ei=60*1e3;function ve(){return reactQuery.queryOptions({queryKey:c.core.dynamicProps(),refetchInterval:ei,staleTime:ei,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=C(t.total_vesting_shares).amount,a=C(t.total_vesting_fund_hive).amount,u=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(u=a/s*1e6);let p=C(r.current_median_history.base).amount,l=C(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=C(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",O=Number(i.content_constant??0),x=String(o.current_hardfork_version??"0.0.0"),A=Number(o.last_hardfork??0),P=t.hbd_print_rate,L=t.hbd_interest_rate,U=t.head_block_number,B=a,Q=s,$=C(t.virtual_supply).amount,ke=t.vesting_reward_percent||0,Ze=n.account_creation_fee;return {hivePerMVests:u,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:O,currentHardforkVersion:x,lastHardfork:A,hbdPrintRate:P,hbdInterestRate:L,headBlock:U,totalVestingFund:B,totalVestingShares:Q,virtualSupply:$,vestingRewardPercent:ke,accountCreationFee:Ze,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function yg(e="post"){return reactQuery.queryOptions({queryKey:c.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function qe(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var c={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>qe("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>qe("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>qe("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>qe("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>qe("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>qe("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>qe("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"],resourceParams:()=>["resource-credits","resource-params"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function fr(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=0;for(let r=0;r=55296&&n<=56319&&r+1>>=7;while(r>0);return t}function Ag(e){return reactQuery.queryOptions({queryKey:c.ai.prices(),queryFn:async()=>{let r=await _()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function Eg(e,t){return reactQuery.queryOptions({queryKey:c.ai.assistPrices(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function Tg(e,t){return reactQuery.queryOptions({queryKey:c.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function Ys(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ig(e,t){return reactQuery.useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??Ys()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let u=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw u.status=i.status,u.data=a,u}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:c.points._prefix(e)});}})}function Zs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ng(e,t){return reactQuery.useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Zs()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.assistPrices(e)}));}})}function ta(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ug(e,t){return reactQuery.useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??ta()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),u={};try{u=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:u})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.transcribePrice(e)}));}})}function mr(e){return !e.posting_json_metadata&&!e.json_metadata}function na(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function N(e){return reactQuery.queryOptions({queryKey:c.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(mr(i)&&na(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!mr(l[0])));if(p[0]&&!mr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=Ie(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,u=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:u,profile:o}},enabled:!!e,staleTime:6e4})}var ia=new Set(["__proto__","constructor","prototype"]);function Rt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ti(e,t){let r={...e};for(let n of Object.keys(t)){if(ia.has(n))continue;let i=t[n],o=r[n];Rt(i)&&Rt(o)?r[n]=ti(o,i):r[n]=i;}return r}function oa(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function Ie(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function ri(e){return Ie(e?.posting_json_metadata)}function ni(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ie(e.posting_json_metadata)).length;return Object.keys(Ie(t.posting_json_metadata)).length>r?t:e}function sa(e){if(!e)return {};try{let t=JSON.parse(e);if(Rt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ii({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=sa(e),i=Rt(n.profile)?n.profile:{},o=gr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function gr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=ti(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=oa(s.tokens),s.version=2,s}function Ft(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Ie(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function aa(e){return new TextEncoder().encode(e).length}function Le(e){return e?aa(e)<=16:false}function iy(e){return reactQuery.queryOptions({queryKey:c.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Le);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ft(r??[])}})}function uy(e){return reactQuery.queryOptions({queryKey:c.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function my(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:c.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function wy(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:c.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var oi=1e3,fa=20;function Oy(e){return reactQuery.queryOptions({queryKey:c.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthLe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Dy(e,t=5,r=[]){return reactQuery.queryOptions({queryKey:c.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var ha=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function My(e,t){return reactQuery.queryOptions({queryKey:c.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,u=typeof a.token=="string"?a.token:void 0;if(!u)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:u,currency:u,address:f,show:y,type:"CHAIN",meta:l},O=[];for(let[x,A]of Object.entries(p))typeof x=="string"&&(ha.has(x)||typeof A!="string"||!A||/^[A-Z0-9]{2,10}$/.test(x)&&O.push({symbol:x,currency:x,address:A,show:y,type:"CHAIN",meta:{address:A,show:y}}));return [h,...O]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function si(e,t){return reactQuery.queryOptions({queryKey:c.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function Gy(e){return reactQuery.queryOptions({queryKey:c.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Xy(e,t){return reactQuery.queryOptions({queryKey:c.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Zy(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function nh(e,t){return reactQuery.queryOptions({queryKey:c.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function ih(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ch(e,t,r){return reactQuery.queryOptions({queryKey:c.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await _()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function dh(e,t){return reactQuery.queryOptions({enabled:!!e&&!!t,queryKey:c.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await _()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function hh(e){return reactQuery.queryOptions({enabled:!!e,queryKey:c.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function Ph(e,t=50){return reactQuery.queryOptions({queryKey:c.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Le(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var D=re.operations,ai={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.fill_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay]},Ca=Array.from(new Set(Object.values(ai).flat()));function Ta(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ra(e){return e.replace(/_operation$/,"")}function Fa(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function qa(e){if(!Fa(e))return e;let t=C(e),r=Tt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Ia(e){let t={};for(let[r,n]of Object.entries(e))t[r]=qa(n);return t}function Rh(e,t=20,r=""){let n=r?ai[r]:Ca;return reactQuery.infiniteQueryOptions({queryKey:c.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await ee("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ra(m.op.type);return {...Ia(m.op.value),num:Ta(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),u=await s(i),p=a(u),l=i??u.total_pages;if(i===null&&p.length1)try{let f=await s(u.total_pages-1);p=[...p,...a(f)],l=u.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function Dh(){return reactQuery.queryOptions({queryKey:c.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Mh(e){return reactQuery.infiniteQueryOptions({queryKey:c.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=exports.ConfigManager.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Vh(e){return reactQuery.queryOptions({queryKey:c.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function zh(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return reactQuery.infiniteQueryOptions({queryKey:c.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Qa=30;function e_(e,t,r){return reactQuery.queryOptions({queryKey:c.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(u=>t==="following"?u.following:u.follower).filter(u=>u.toLowerCase().includes(r.toLowerCase())).slice(0,Qa);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(u=>({name:u.name,full_name:u.metadata.profile?.name||"",reputation:u.reputation,active:u.active}))??[]}})}function o_(e=20){return reactQuery.infiniteQueryOptions({queryKey:c.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function l_(e=250){return reactQuery.infiniteQueryOptions({queryKey:c.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Xn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function $e(e,t){return reactQuery.queryOptions({queryKey:c.posts.fragments(e),queryFn:async()=>t?(await _()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function g_(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function w_(e="feed"){return reactQuery.queryOptions({queryKey:c.posts.promoted(e),queryFn:async()=>{let t=exports.ConfigManager.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await _()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function O_(e){return reactQuery.queryOptions({queryKey:c.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function C_(e,t,r){return reactQuery.queryOptions({queryKey:c.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function I_(e,t){return reactQuery.queryOptions({queryKey:c.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function M_(e,t){return reactQuery.queryOptions({queryKey:c.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function j_(e,t){return reactQuery.queryOptions({queryKey:c.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function te(e){return Array.isArray(e)?e.map(t=>ci(t)):ci(e)}function ci(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function ui(e,t,r){try{let n=await Et("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function pi(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return reactQuery.queryOptions({queryKey:c.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let u=await ui(e,i,r);if(!u)return null;let p=n!==void 0?{...u,num:n}:u;return te(p)}let a=n!==void 0?{...s,num:n}:s;return te(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function se(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function li(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await Xa(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function di(e,t,r){let n=e.map(st),i=await Promise.all(n.map(o=>li(o,t,void 0,r)));return te(i)}async function fi(e,t="",r="",n=20,i="",o="",s){let a=await se("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function yr(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await se("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function st(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Xa(e="",t="",r="",n,i){let o=await se("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=st(o),a=await li(s,r,n,i);return te(a)}}async function ow(e="",t=""){let r=await se("get_post_header",{author:e,permlink:t});return r&&st(r)}async function mi(e,t,r){let n=await se("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=st(s);return i}return n}async function gi(e,t=""){return se("get_community",{name:e,observer:t})}async function sw(e="",t=100,r,n="rank",i=""){return se("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function yi(e){let t=await se("normalize_post",{post:e});return t&&st(t)}async function aw(e){return se("list_all_subscriptions",{account:e})}async function cw(e){return se("list_subscribers",{community:e})}async function uw(e,t){return se("get_relationship_between_accounts",[e,t])}async function qt(e,t){return se("get_profiles",{accounts:e,observer:t})}var _i=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(_i||{});function hr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Za(e,t,r){let n=l=>hr(l.pending_payout_value).amount+hr(l.author_payout_value).amount+hr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[u];return u>=0&&(a.splice(u,1),a.unshift(p)),a}function wi(e,t="created",r=true,n){let i=n||d.defaultObserver;return reactQuery.queryOptions({queryKey:c.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return te(s)},enabled:r&&!!e,select:o=>Za(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),u=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!u.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function yw(e,t,r,n=true){let i=r||d.defaultObserver;return reactQuery.queryOptions({queryKey:c.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>mi(e,t,i)})}function Pw(e,t="posts",r=20,n="",i=true){return reactQuery.infiniteQueryOptions({queryKey:c.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await yr(t,e,o.author??"",o.permlink??"",r,n,s);return te(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Ow(e,t="posts",r="",n="",i=20,o="",s=true){return reactQuery.queryOptions({queryKey:c.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let u=await yr(t,e,r,n,i,o,a);return te(u??[])}})}var bi=new Map;function ic(e){let t=bi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>oc(n,e))}),bi.set(e,t)),t}function oc(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function Fw(e,t,r=20,n="",i=true,o={}){return reactQuery.infiniteQueryOptions({queryKey:c.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let u=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(u="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:u,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return te(p)},select:ic(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function qw(e,t="",r="",n=20,i="",o="",s=true){return reactQuery.queryOptions({queryKey:c.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let u=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(u="");let p=await fi(e,t,r,n,u,o,a);return te(p??[])}})}function Nw(e,t,r=200){return reactQuery.queryOptions({queryKey:c.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function Vw(e,t){return reactQuery.queryOptions({queryKey:c.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Ww(e,t){return reactQuery.queryOptions({queryKey:c.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Gw(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Xw(e,t){return reactQuery.queryOptions({queryKey:c.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Zw(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Ai(e){let r=await _()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function nb(e,t){return reactQuery.queryOptions({queryKey:c.posts.images(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function ib(e,t){return reactQuery.queryOptions({queryKey:c.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function ob(e,t,r=10){return reactQuery.infiniteQueryOptions({queryKey:c.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ub(e,t,r=false){return reactQuery.queryOptions({queryKey:c.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function gc(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function fb(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?gc(n,r):"";return reactQuery.queryOptions({queryKey:c.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:u,tags:p}=s.list[0];return {body:a,title:u,tags:p}},enabled:i})}function hb(e,t,r=true){return reactQuery.queryOptions({queryKey:c.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function hc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function _c(e){return {...e,id:e.id??e.post_id}}function me(e,t){if(!e)return null;let r=e.container??e,n=hc(r,t),i=e.parent?_c(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function wc(e){return Array.isArray(e)?e:[]}async function Pi(e){let t=wi(e,"created",true),r=await d.queryClient.fetchQuery(t),n=wc(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function Oi(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var Ac=20;function xi(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Ac}}async function Ei({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let u=exports.ConfigManager.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",u);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=me(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function xb(e={}){let t=xi(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return reactQuery.infiniteQueryOptions({queryKey:c.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:u,signal:p})=>Ei(t,u,p),getNextPageParam:u=>{if(!(u.lengthEi(t,void 0,u)})}var Oc=20;function xc(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Oc}}async function Ec({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=exports.ConfigManager.getValidatedBaseUrl(),u=new URL("/private-api/waves/shorts",a);u.searchParams.set("limit",String(i)),o&&u.searchParams.set("cursor",o),e.forEach(f=>u.searchParams.append("container",f)),t&&u.searchParams.set("tag",t),r&&u.searchParams.set("author",r),n&&u.searchParams.set("observer",n);let p=await fetch(u.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=me(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Rb(e={}){let t=xc(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return reactQuery.infiniteQueryOptions({queryKey:c.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:u})=>Ec(t,a,u),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of u){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Pi(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:Oi(f,l,e)}}let p=u[u.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Nb(e){return reactQuery.infiniteQueryOptions({queryKey:c.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await Tc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Fc=40;function Vb(e,t,r=Fc){return reactQuery.infiniteQueryOptions({queryKey:c.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>me(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function Gb(e,t){let r=t?.trim().toLowerCase();return reactQuery.infiniteQueryOptions({queryKey:c.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>me(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function Xb(e,t=24){let r=e?.trim()||void 0;return reactQuery.queryOptions({queryKey:c.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:u,posts:p})=>({tag:u,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function nv(e,t){let r=t?.trim().toLowerCase();return reactQuery.infiniteQueryOptions({queryKey:c.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>me(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function av(e){return reactQuery.queryOptions({queryKey:c.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=exports.ConfigManager.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function dv(e,t=true){return reactQuery.queryOptions({queryKey:c.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>yi(e)})}function Mc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Si(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function bv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return reactQuery.infiniteQueryOptions({queryKey:c.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Si(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(pi(m.author,m.permlink));Mc(y)&&l.push(y);}let[f]=a;return {lastDate:f?Si(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function xv(e,t,r=true){return reactQuery.queryOptions({queryKey:c.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>qt(e,t)})}function Rv(e,t="HIVE",r=200){return reactQuery.infiniteQueryOptions({queryKey:c.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await ee("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function Kv(e,t="HIVE",r="yearly"){return reactQuery.queryOptions({queryKey:c.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ee("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Qv(){return reactQuery.queryOptions({queryKey:c.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function Hv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Wv(e,t,r){let n=reactQuery.useQueryClient(),{data:i}=reactQuery.useQuery(N(e));return v(["accounts","update"],e,o=>{let s=ni(n.getQueryData(N(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ii({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(N(e).queryKey,a=>{if(!a)return a;let u=JSON.parse(JSON.stringify(a));return u.profile=gr({existingProfile:ri(a),profile:s.profile,tokens:s.tokens}),u}),await S(t?.adapter,r,[c.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...N(e),staleTime:0});}catch{}}})}function Xv(e,t,r,n,i){return reactQuery.useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=si(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await zn(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(c.accounts.relations(e,t),o),t&&b().invalidateQueries(N(t));}})}function _r(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function De(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function Ke(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function wr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function br(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Be(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Wc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Be(e,o.trim(),r,n))}function Gc(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function We(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function Ne(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function ki(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function at(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ne(e,t,r,n,i),ki(e,i)]}function ct(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function ut(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function pt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function lt(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function dt(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function vr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Me(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function Ar(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Pr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function Or(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function It(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function zc(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Jc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return It(e,t)}function xr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function Er(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function Sr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function kr(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function Cr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function Yc(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function Xc(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Rr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Fr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function qr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Ir(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Dr(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function Zc(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function eu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var Ci=(r=>(r.Buy="buy",r.Sell="sell",r))(Ci||{}),Ti=(r=>(r.EMPTY="",r.SWAP="9",r))(Ti||{});function Kt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function Dt(e,t=3){return e.toFixed(t)}function tu(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,u=n==="buy"?`${Dt(t,3)} HBD`:`${Dt(t,3)} HIVE`,p=n==="buy"?`${Dt(r,3)} HIVE`:`${Dt(r,3)} HBD`;return Kt(e,u,p,false,s,a)}function Kr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Br(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function ru(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function nu(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Nr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Mr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Qr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Hr(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let u={...t,account_auths:a};return u.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:u,memo_key:i,json_metadata:o}]}function iu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function ou(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function su(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function au(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Ur(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Vr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function jr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Ge(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function cu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>Ge(e,o.trim(),r,n))}function Lr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function uu(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function pu(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function wA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Or(e,n)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function PA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[It(e,n)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function SA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function RA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function DA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:n})}function QA(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=c.accounts.favorites(e),a=c.accounts.favoritesInfinite(e),u=c.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:u})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(u);o.setQueryData(u,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(O=>({...O,data:O.data.filter(x=>x.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);s?.previousCheck!==void 0&&a.setQueryData(c.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function hu(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Ri(e,t){let{data:r}=reactQuery.useQuery(N(e));return reactQuery.useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let u=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=hu(y,n.map((h,O)=>[h[p].createPublic().toString(),O+1])),l};return Z([["account_update",{account:e,json_metadata:r.json_metadata,owner:u("owner"),active:u("active"),posting:u("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function JA(e,t){let{data:r}=reactQuery.useQuery(N(e)),{mutateAsync:n}=Ri(e);return reactQuery.useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,i,"owner"),active:H.fromLogin(e,i,"active"),posting:H.fromLogin(e,i,"posting"),memo_key:H.fromLogin(e,i,"memo")}]})},...t})}function rP(e,t,r){let n=reactQuery.useQueryClient(),{data:i}=reactQuery.useQuery(N(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let u=JSON.parse(JSON.stringify(i.posting));u.account_auths=u.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:u,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return Z([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),Gn__default.default.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(N(e).queryKey,u=>({...u,posting:{...u?.posting,account_auths:u?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function uP(e,t,r,n){let{data:i}=reactQuery.useQuery(N(e));return reactQuery.useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:u})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await _()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:u,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Z([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),Gn__default.default.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function lP(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function Fi(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([u])=>!r.has(u.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function hP(e,t){let{data:r}=reactQuery.useQuery(N(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=Fi(r,o);return Z([["account_update",s]],n)},...t})}function vP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Qr(n,i)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function xP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Hr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await S(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}function CP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Mr(e,n.newAccountName,n.keys):Nr(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}var $r=300*60*24,Cu=1e4,Tu=5e7;function qi(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,i=C(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Ru(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Fu(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function qu(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=qi(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Cu/(n*$r)),a=lr(e),u=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(u)||s>u?0:Math.max(s-Tu,0)}function Iu(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Fu(t))return qu(e,t,n);let i=0;try{if(i=qi(e),!Number.isFinite(i))return 0}catch{return 0}return Ru(i,r,n)}function qP(e){return lr(e).percentage/100}function IP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*$r/1e4}function DP(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/$r;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function KP(e){return kt(e).percentage/100}function BP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let u=Iu(e,t,r,n);return Number.isFinite(u)?u/i*o*(s/a):0}var Du={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Ku(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Bu(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function Nu(e){let t=e[0];return t==="custom_json"?Ku(e):t==="create_proposal"||t==="update_proposal"?Bu(e):Du[t]??"posting"}function MP(e){let t="posting";for(let r of e){let n=Nu(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function jP(e){return reactQuery.useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):jn(r)?n=H.fromString(r):n=H.from(r),Z([t],n)}})}function WP(e,t,r="active"){return reactQuery.useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function YP(e="/"){return reactQuery.useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Gn__default.default.sendOperation(t,{callback:e},()=>{})})}function t0(){return reactQuery.queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ii(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Di(e,t){return {...e??{},title:t.title,body:t.body}}function u0(e,t){return reactQuery.useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await _()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Di(r,n);i.setQueryData($e(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,u)=>u===0?{...a,data:[o,...a.data]}:a)});}})}function y0(e,t){return reactQuery.useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ii(s,r,n);i.setQueryData($e(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(u=>u.id===n.fragmentId?o(u):u)}))});}})}function A0(e,t){return reactQuery.useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await _()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData($e(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function G(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function x0(e,t,r,n){let o=await _()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await G(o);return {status:o.status,data:s}}async function E0(e){let r=await _()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await G(r);return {status:r.status,data:n}}async function S0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await _()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await G(s);}async function k0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await _()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(s)}async function C0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},u=await _()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(u)}async function T0(e,t,r){let n={code:e,username:t,token:r},o=await _()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function Ki(e,t){let r={code:e};t&&(r.id=t);let i=await _()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Bi(e,t){let r={code:e,url:t},i=await _()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}var Wu="https://i.ecency.com";async function Ni(e,t,r){let n=_(),i=new FormData;i.append("file",e);let o=await n(`${Wu}/hs/${t}`,{method:"POST",body:i,signal:r});return G(o)}async function R0(e,t,r,n){let i=_(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return G(s)}async function Mi(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Qi(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await _()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(a)}async function Hi(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},u=await _()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(u)}async function Ui(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Vi(e,t,r,n,i,o,s,a){let u={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(u.options=o);let l=await _()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return G(l)}async function ji(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Li(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function F0(e,t,r){let n={code:e,author:t,permlink:r},o=await _()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function q0(e,t,r){let n={username:e,email:t,friend:r},o=await _()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}function N0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return Qi(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(c.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function V0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:u})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Hi(t,i,o,s,a,u)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function z0(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return Ui(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=c.posts.drafts(e),a=c.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let u=o.getQueryData(s);u&&o.setQueryData(s,u.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:u,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);n?.(i);}})}function eO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:u,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Vi(t,i,o,s,a,u,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function oO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return ji(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function pO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return Li(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)}),o.invalidateQueries({queryKey:c.posts.drafts(e)});},onError:n})}function gO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Bi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.images(e)});},onError:n})}function bO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Mi(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],u=>u?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},u=>u&&{...u,pages:u.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function OO(e,t){return reactQuery.useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Ni(r,n,i),onSuccess:e,onError:t})}function Nt(e,t){return `/@${e}/${t}`}function np(e,t,r){return (r??b()).getQueryData(c.posts.entry(Nt(e,t)))}function ip(e,t){(t??b()).setQueryData(c.posts.entry(Nt(e.author,e.permlink)),e);}function Bt(e,t,r,n){let i=n??b(),o=Nt(e,t),s=i.getQueryData(c.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(c.posts.entry(o),a),s}exports.EntriesCacheManagement=void 0;(a=>{function e(u,p,l,f,m){Bt(u,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(u,p,l,f){Bt(u,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(u,p,l,f){Bt(u,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(u,p,l,f){Bt(p,l,m=>({...m,children:m.children+1,replies:[u,...m.replies]}),f);}a.addReply=n;function i(u,p){u.forEach(l=>ip(l,p));}a.updateEntries=i;function o(u,p,l){(l??b()).invalidateQueries({queryKey:c.posts.entry(Nt(u,p))});}a.invalidateEntry=o;function s(u,p,l){return np(u,p,l)}a.getEntry=s;})(exports.EntriesCacheManagement||={});function op(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function sp(e,t,r){let n=exports.EntriesCacheManagement.getEntry(t.author,t.permlink,r);if(!n?.active_votes||op(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);exports.EntriesCacheManagement.updateVotes(t.author,t.permlink,i,o,r);}function RO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[_r(e,n,i,o)],async(n,i)=>{sp(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function KO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[br(e,n,i,o??false)],async(n,i)=>{let o=exports.EntriesCacheManagement.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));exports.EntriesCacheManagement.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:c.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function QO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Ke(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let u=[c.accounts.full(e),c.resourceCredits.account(e)];if(!o){u.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;u.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(u);}},t,"posting",{broadcastMode:r})}function VO(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function $i(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[u,p]of a)p&&(s.set(u,p),o.setQueryData(u,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Wi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function jO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(c.posts.entry(o));return s&&i.setQueryData(c.posts.entry(o),{...s,...r}),s}function LO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(c.posts.entry(o),r);}function JO(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[wr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:$i(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Wi(s);}})}function ex(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true}=n.options;i.push(Ke(n.author,n.permlink,o,s,a,u,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function ix(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Ke(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[c.resourceCredits.account(e)];s.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,u=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===u}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function cx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[jr(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.posts._promotedPrefix],[...c.points._prefix(e)],c.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var ap=[3e3,3e3,3e3],cp=e=>new Promise(t=>setTimeout(t,e));async function up(e,t){return g("condenser_api.get_content",[e,t])}async function pp(e,t,r=0,n){let i=n?.delays??ap,o;try{o=await up(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await cp(s),pp(e,t,r+1,n)}var ze={};ht(ze,{useRecordActivity:()=>Wr});function dp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Wr(e,t,r){return reactQuery.useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=_(),i=dp(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function _x(e){return reactQuery.queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function Px(e){return reactQuery.queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function Sx(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return reactQuery.queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Mt="threespeakfund",qx=1100;function yp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function Ix(e,t){if(!yp(t))return e;let r=e.find(n=>n.account===Mt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Mt?{...n,weight:1100}:n):[...e,{account:Mt,weight:1100}]}function Dx(e){return e===Mt}var Jr={};ht(Jr,{getAccountTokenQueryOptions:()=>zr,getAccountVideosQueryOptions:()=>Ap});var Gr={};ht(Gr,{getDecodeMemoQueryOptions:()=>wp});function wp(e,t,r){return reactQuery.queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Gn__default.default.Client({accessToken:r}).decode(t)}})}var Gi={queries:Gr};function zr(e,t){return reactQuery.queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await _()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=Gi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function Ap(e,t){return reactQuery.queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=zr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await _()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var Xx={queries:Jr};function iE(e){return reactQuery.queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await _()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function cE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return reactQuery.queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await _()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function dE(){return reactQuery.queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function yE(e){return reactQuery.queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function vE(){return reactQuery.queryOptions({queryKey:c.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await g("rc_api.get_resource_params",{})})}var zi=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var Ji={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function xE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Ji;let{current_mana:i,max_mana:o}=kt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Ji,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,u=s*a,p=iBigInt(typeof e=="string"?e:Math.trunc(e));function Rp(e,t,r,n){if(r<=0||n<=0)return 0;let i=Je(e.coeff_a),o=Je(e.coeff_b),s=Je(e.shift),a=Je(n)*i>>s;a+=1n,a*=Je(r);let u=o+(t>0?Je(t):0n);return u===0n?0:Number(a/u+1n)}function Fp({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:i=false},o){let s=o.resource_state_bytes,a=o.resource_execution_time;return {resource_history_bytes:e,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:s.comment_base_size+s.comment_permlink_char_size*t+s.transaction_base_size+s.comment_beneficiaries_member_size*n,resource_execution_time:a.comment_time+a.transaction_time+a.verify_authority_time*r+(i?a.comment_options_time:0)}}var ge=e=>{let t=fr(e);return je(t)+t},qp=e=>1+ge(e.parent_author)+ge(e.parent_permlink)+ge(e.author)+ge(e.permlink)+ge(e.title)+ge(e.body)+ge(e.json_metadata),Ip=(e,t)=>{let r=t.beneficiaries??[],n=1+ge(e.author)+ge(e.permlink)+Tp+2+2;return n+=je(r.length>0?1:0),r.length>0&&(n+=1+je(r.length),r.forEach(i=>{n+=ge(i.account)+2;})),n};function Dp({op:e,options:t,signatures:r=1}){let n=[qp(e)];return t&&n.push(Ip(e,t)),kp+je(n.length)+n.reduce((i,o)=>i+o,0)+je(r)+Cp*r}var Kp={ready:false,cost:0,transactionBytes:0,breakdown:[]};function CE({op:e,options:t,rcParams:r,rcStats:n,signatures:i=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return Kp;let o=Dp({op:e,options:t,signatures:i}),s=Fp({transactionBytes:o,permlinkLength:fr(e.permlink),signatures:i,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),u=0,p=[];return zi.forEach((l,f)=>{let m=r.resource_params[l],y=Number(n.pool[f]??0),h=Number(n.share[f]??0);if(!m||h<=0)return;let O=s[l]*Number(m.resource_dynamics_params.resource_unit??1),x=Number(BigInt(a)*BigInt(h)/10000n),A=Rp(m.price_curve_params,y,O,x);u+=A,p.push({resource:l,usage:O,cost:A});}),{ready:true,cost:u,transactionBytes:o,breakdown:p}}function qE(e,t,r){return reactQuery.queryOptions({queryKey:["games","status-check",r,e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function NE(e,t,r,n){let{mutateAsync:i}=Wr(e,"spin-rolled");return reactQuery.useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function UE(e){let t=e?.replace("@","");return reactQuery.queryOptions({queryKey:c.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await _()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var Qp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function jE(e,t){return Qp.find(r=>r.tier===e&&r.id===t)}var Hp=25;function Up(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function LE(e){return Up(e)>Hp}var $E=300,WE=2;function Lp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function $p(e){let r=await _()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Lp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function YE(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return $p(t)},onSuccess(){n&&r.invalidateQueries({queryKey:c.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:c.quests.status(n)});}})}function tS(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Tr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function oS(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Rr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function uS(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[Dr(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function fS(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[Fr(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>{if(!a)return a;let u=[...a.team??[]],p=u.findIndex(([l])=>l===o.account);return p>=0?u[p]=[u[p][0],o.role,u[p][2]??""]:u.push([o.account,o.role,""]),{...a,team:u}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)],c.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function hS(e,t,r,n){return v(["communities","update",e],t,i=>[qr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function vS(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Lr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.communities.singlePrefix(i.name)],[...c.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function xS(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Ir(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.posts.entry(`/@${i.account}/${i.permlink}`),[...c.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function TS(e,t,r=100,n=void 0,i=true){return reactQuery.queryOptions({queryKey:c.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function DS(e,t){return reactQuery.queryOptions({queryKey:c.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function QS(e,t="",r=true){return reactQuery.queryOptions({queryKey:c.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>gi(e??"",t)})}var Yi=100;async function Xi(e,t){return await g("bridge.list_subscribers",{community:e,limit:Yi,...t?{last:t}:{}})??[]}function $S(e){return reactQuery.queryOptions({queryKey:c.communities.subscribers(e),queryFn:async()=>Xi(e,null),staleTime:6e4})}function WS(e){return reactQuery.infiniteQueryOptions({queryKey:c.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Xi(e,t),getNextPageParam:t=>t?.length>=Yi?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function ZS(e,t){return reactQuery.infiniteQueryOptions({queryKey:c.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function nk(){return reactQuery.queryOptions({queryKey:c.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var el=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(el||{}),ok={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function ak(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function ck({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function dk(e,t){return reactQuery.queryOptions({queryKey:c.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function yk(e,t,r=void 0){return reactQuery.infiniteQueryOptions({queryKey:c.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var nl=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(nl||{});var il=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))(il||{}),Zi=[1,2,3,4,5,6,10,13,15,19,20,21,22],ol=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(ol||{});function Pk(e,t,r){return reactQuery.queryOptions({queryKey:c.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Zi]})})}function Sk(){return reactQuery.queryOptions({queryKey:c.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function Rk(e){return reactQuery.queryOptions({queryKey:c.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function pl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function eo(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function Nk(e,t,r,n){let i=b();return reactQuery.useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Ki(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:c.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:c.notifications._prefix,predicate:l=>{let f=l.state.data;return eo(f)}});a.forEach(([l,f])=>{if(f&&eo(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>pl(h,o)))};i.setQueryData(l,m);}});let u=c.notifications.unreadCount(e),p=i.getQueryData(u);return typeof p=="number"&&p>0&&(s.push([u,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(u,p-1):i.setQueryData(u,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(c.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([u,p])=>{i.setQueryData(u,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:c.notifications._prefix});}})}function Uk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>xr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function $k(e){return reactQuery.queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function rC(e,t,r){return reactQuery.infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),u=Ft(a);return s.map(l=>({...l,voterAccount:u.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function sC(e){return reactQuery.queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function pC(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[Cr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.proposals.list(),c.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function mC(e,t,r){return v(["proposals","create"],e,n=>[kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.proposals.list()]);},t,"active",{broadcastMode:r})}function _C(e,t=50){return reactQuery.infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthee("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function EC(e){return reactQuery.queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function TC(e){return reactQuery.queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function IC(e){return reactQuery.queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function NC(e){return reactQuery.queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function UC(e){return reactQuery.queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function $C(e){return reactQuery.queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function YC(e,t=100){return reactQuery.infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function tT(e){return reactQuery.queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await _()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function oT(e){return reactQuery.queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function uT(e){return reactQuery.queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function le(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function kl(e){if(!e||typeof e!="object")return;let t=e;return {name:le(t.name)??"",symbol:le(t.symbol)??"",layer:le(t.layer)??"hive",balance:ae(t.balance)??0,fiatRate:ae(t.fiatRate)??0,currency:le(t.currency)??"usd",precision:ae(t.precision)??3,address:le(t.address),error:le(t.error),pendingRewards:ae(t.pendingRewards),pendingRewardsFiat:ae(t.pendingRewardsFiat),liquid:ae(t.liquid),liquidFiat:ae(t.liquidFiat),savings:ae(t.savings),savingsFiat:ae(t.savingsFiat),staked:ae(t.staked),stakedFiat:ae(t.stakedFiat),iconUrl:le(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ae(t.apr)}}function Cl(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function Tl(e){if(!e||typeof e!="object")return;let t=e;return le(t.username)??le(t.name)??le(t.account)}function to(e,t="usd",r=true){return reactQuery.queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${exports.ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=Cl(o).map(a=>kl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:Tl(o)??e,currency:le(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Qt(e){return reactQuery.queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(ve().queryKey),r=b().getQueryData(N(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function ro(e){return reactQuery.queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(N(e).queryKey),r=b().getQueryData(ve().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:C(t.hbd_balance).amount+C(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:C(t.hbd_balance).amount},{name:"savings",balance:C(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Il(e){let u=9.5-(e.headBlock-7e6)/25e4*.01;u<.95&&(u=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*u*p/f).toFixed(3)}function no(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(ve().queryKey),r=b().getQueryData(N(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=C(r.vesting_shares).amount,a=C(r.delegated_vesting_shares).amount,u=C(r.received_vesting_shares).amount,p=C(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=Zn(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ve(s,t.hivePerMVests).toFixed(3),y=+Ve(a,t.hivePerMVests).toFixed(3),h=+Ve(u,t.hivePerMVests).toFixed(3),O=+Ve(l,t.hivePerMVests).toFixed(3),x=+Ve(f,t.hivePerMVests).toFixed(3),A=Math.max(m-O,0),P=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+A.toFixed(3),apr:Il(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+P.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...O>0?[{name:"pending_power_down",balance:+O.toFixed(3)}]:[],...x>0&&x!==O?[{name:"next_power_down",balance:+x.toFixed(3)}]:[]]}}})}var K=re.operations,Yr={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay],"":[]};var IT=Object.keys(re.operations);var io=re.operations,BT=io,NT=Object.entries(io).reduce((e,[t,r])=>(e[r]=t,e),{});var oo=re.operations;function Kl(e){return Object.prototype.hasOwnProperty.call(oo,e)}function ft(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in Yr){Yr[a].forEach(u=>o.add(u));return}Kl(a)&&o.add(oo[a]);});let s=Ml(Array.from(o));return {filterKey:i,filterArgs:s}}function Xr(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Bl(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Nl(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Ml(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,Nl(Number(s),t),...n])).map(u=>({num:u[0],type:u[1].op[0],timestamp:u[1].timestamp,trx_id:u[1].trx_id,...u[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return C(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=C(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return C(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function zT(e,t=20,r=[]){let{filterKey:n}=ft(r),i=Xr(r);return reactQuery.infiniteQueryOptions({...Ht(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(u=>{switch(u.type){case "author_reward":case "comment_benefactor_reward":return C(u.hbd_payout).amount>0;case "claim_reward_balance":return C(u.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(u.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return C(u.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=C(u.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(u.type)}}))})})}function eR(e,t=20,r=[]){let{filterKey:n}=ft(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return reactQuery.infiniteQueryOptions({...Ht(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.vesting_payout).amount>0;case "claim_reward_balance":return C(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(C(p.amount).symbol);case "fill_recurrent_transfer":let m=C(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function so(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Zr(e,t){return new Date(e.getTime()-t*1e3)}function iR(e=86400){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,so(t),so(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[Zr(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[Zr(n,Math.max(100*e,28800)),Zr(n,e)]})}function cR(e){return reactQuery.queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function dR(e,t=50){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function hR(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>C(n.vesting_shares).amount-C(r.vesting_shares).amount)})}function vR(e=500){return reactQuery.queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function xR(){return reactQuery.queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function CR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return reactQuery.queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function qR(){return reactQuery.queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function BR(e,t,r,n){return reactQuery.queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ao(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function HR(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return reactQuery.queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[ao(i),ao(n),e])})}function LR(){return reactQuery.queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function zR(){return reactQuery.queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function ZR(e,t,r){return v(["market","limit-order-create"],e,n=>[Kt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function mt(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function sF(e,t,r,n){let i=_(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return mt(s)}async function co(e){if(e==="hbd")return 1;let t=_(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await mt(n)).hive_dollar[e]}async function aF(e,t){let n=await _()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return mt(n)}async function cF(){let t=await _()(d.privateApiHost+"/private-api/market-data/latest");return mt(t)}async function uF(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return mt(t)}var ed={"Content-type":"application/json"};async function td(e){let t=_(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:ed});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ee(e,t){try{return await td(e)}catch{return t}}async function dF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([Ee({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ee({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((u,p)=>{let l=Number(u.price??0);return Number(p.price??0)-l}),s=a=>a.sort((u,p)=>{let l=Number(u.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function fF(e,t=50){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function mF(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([Ee({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ee({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),u=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...u].sort((p,l)=>l.timestamp-p.timestamp)}async function rd(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Ee({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Ye(e,t){return rd(t,e)}async function Ut(e){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Vt(e){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function uo(e,t,r,n){let i=_(),o=exports.ConfigManager.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function po(e,t="daily"){let r=_(),n=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function lo(e){let t=_(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function jt(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ut(e)})}function vF(){return reactQuery.queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ye()})}function fo(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Vt(e)})}function kF(e,t,r=20){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return uo(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function FF(e,t="daily"){return reactQuery.queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>po(e,t)})}function KF(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await lo(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function mo(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ye(e,t)})}function Xe(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,u=typeof a=="string"?parseFloat(a):a;return s+=u.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var Lt=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${Xe(this.stake,{fractionDigits:this.precision})} + ${Xe(this.delegationsIn,{fractionDigits:this.precision})} - ${Xe(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():Xe(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():Xe(this.balance,{fractionDigits:this.precision})};function WF(e,t,r){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await Ut(e),i=await Vt(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),u=[...s,...a.length?await Ye(void 0,a):[]];return n.map(p=>{let l=i.find(x=>x.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=u.find(x=>x.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),O=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new Lt({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:O})})},enabled:!!e})}function go(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Qt(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(fo([t])),s=await r.ensureQueryData(jt(e)),a=await r.ensureQueryData(mo(void 0,t)),u=o?.find(x=>x.symbol===t),p=s?.find(x=>x.symbol===t),f=+(a?.find(x=>x.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),O=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&O.push({name:"unstaking",balance:h}),{name:t,title:u?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:O}}})}function gt(e,t=0){return reactQuery.queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function yo(e){return reactQuery.queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(gt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(gt(e).queryKey)?.points??0)})})}function lq(e,t){return reactQuery.queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:u,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:u??void 0,to:p??void 0,memo:l??void 0}))})}function Pq(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await co(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=to(e,i,true),u=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let x=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(x){let A=Math.abs(Number.parseFloat(x[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:A}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:A}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:A});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return reactQuery.queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await u();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Qt(e));else if(t==="HP")l=await o(no(e));else if(t==="HBD")l=await o(ro(e));else if(t==="POINTS")l=await o(yo(e));else if((await n.ensureQueryData(jt(e))).some(m=>m.symbol===t))l=await o(go(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var yd=(A=>(A.Transfer="transfer",A.TransferToSavings="transfer-saving",A.WithdrawFromSavings="withdraw-saving",A.Delegate="delegate",A.PowerUp="power-up",A.PowerDown="power-down",A.WithdrawRoutes="withdraw-routes",A.ClaimInterest="claim-interest",A.Swap="swap",A.Convert="convert",A.Gift="gift",A.Promote="promote",A.Claim="claim",A.Buy="buy",A.Stake="stake",A.Unstake="unstake",A.Undelegate="undelegate",A))(yd||{});function Cq(e,t,r){return v(["wallet","transfer"],e,n=>[Be(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Iq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ge(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Mq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[pt(e,n.delegatee,n.vestingShares)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function jq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[lt(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await S(t?.adapter,r,[c.wallet.withdrawRoutes(e),c.accounts.full(e),c.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function Gq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Zq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[We(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function iI(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ne(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function uI(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[ct(e,n.to,n.amount)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function mI(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ut(e,n.vestingShares)],async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wI(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?vr(e,n.amount,n.requestId):dt(e,n.amount,n.requestId)],async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function OI(e,t,r){return v(["wallet","claim-interest"],e,n=>at(e,n.to,n.amount,n.memo,n.requestId),async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var hd=5e3,$t=new Map;function CI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Br(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],c.assets.hiveGeneralInfo(e),c.assets.hbdGeneralInfo(e),c.assets.hivePowerGeneralInfo(e)],o=$t.get(n);o&&(clearTimeout(o),$t.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{$t.delete(n);}},hd);$t.set(n,s);},t,"posting",{broadcastMode:r})}function qI(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function BI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function HI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function LI(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function zI(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function ZI(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _d(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Be(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Ne(n,i,o,s,a)];case "power-up":return [ct(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Be(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Ne(n,i,o,s,a)];case "claim-interest":return at(n,i,o,s,a);case "convert":return [dt(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ut(n,o)];case "delegate":return [pt(n,i,o)];case "withdraw-routes":return [lt(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ge(n,i,o,s)];break}return null}function wd(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [Me(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [Me(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [Me(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [Me(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [Me(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [Ar(n,[e])]}return null}function bd(e){return e==="claim"?"posting":"active"}function oD(e,t,r,n,i){let{mutateAsync:o}=ze.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=_d(t,r,s);if(a)return a;let u=wd(t,r,s);if(u)return u;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,bd(r),{broadcastMode:i})}function uD(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[Pr(e,n,i)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),c.resourceCredits.account(e),c.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function fD(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[Er(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function hD(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Sr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function Ad(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function PD(e){return reactQuery.infiniteQueryOptions({queryKey:c.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ee("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(Ad),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function OD(e,t,r,n="vests",i="desc"){return reactQuery.queryOptions({queryKey:c.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await ee("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function xD(e){return reactQuery.queryOptions({queryKey:c.witnesses.voterCount(e),queryFn:async()=>await ee("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Pd=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(Pd||{});async function xd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await _()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function FD(e,t,r,n){let{mutateAsync:i}=ze.useRecordActivity(e,"points-claimed");return reactQuery.useMutation({mutationFn:()=>xd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(gt(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var _o=/(^|\s)author:([^\s]+)/g,wo=/(^|\s)type:([^\s]+)/g,bo=/(^|\s)category:([^\s]+)/g,vo=/(^|\s)tag:([^\s]+)/g;var Po=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Po||{}),ID=5,DD=100;function Oo(e){return e.trim().split(/\s+/)[0]??""}function Ed(e){return Oo(e).replace(/^@+/,"").toLowerCase()}function Sd(e){return Oo(e).replace(/^#+/,"").toLowerCase()}function kd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function KD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=Ed(t),a=Sd(n),u=kd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),u.length>0&&p.push(`tag:${u.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:u}}var Ao=class{query="";search="";author="";type="";category="";tags=[];constructor(t){this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}grab=t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""};grabAuthor=()=>{this.author=this.grab(_o);};grabType=()=>{let t=this.grab(wo);Object.values(Po).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(bo);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(vo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([_o,wo,bo,vo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();}};async function Ae(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Se(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var Td=reactQuery.isServer?0:3;function yt(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let u=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(be,s)});return Ae(u,Se)},retry:yt})}function WD(e,t,r=true){return reactQuery.infiniteQueryOptions({queryKey:c.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",u=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:u,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:we(be,i)});return Ae(y,Se)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:yt})}async function YD(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await _()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(be,s)});return Ae(p,Se)}async function xo(e,t,r=be){let i=await _()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:we(r,t)});return Ae(i,Se)}async function XD(e,t){let n=await _()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:we(be,t)}),i=await Ae(n,Array.isArray);return i?.length>0?i:[e]}var Id=4368*60*60*1e3,Dd=4,Kd=3e3,Bd=2e3,Nd=4e3,nK=2;function Md(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Qd(e){let t=5381;for(let r=0;r>>0).toString(36)}function iK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Md(e.body??"",Kd),o=Qd(`${t}|${n.join(",")}|${i}`);return reactQuery.queryOptions({queryKey:c.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Id).toISOString().slice(0,19),u=await xo({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?Bd:Nd),p=[],l=new Set;for(let f of u.results){if(p.length>=Dd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function pK(e,t=5){let r=e.trim();return reactQuery.queryOptions({queryKey:c.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:qt(n)},enabled:!!r})}function gK(e,t=10){let r=e.trim();return reactQuery.queryOptions({queryKey:c.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function vK(e,t,r,n,i,o){return reactQuery.infiniteQueryOptions({queryKey:c.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let u={q:e,sort:t,hide_low:r};n&&(u.since=n),s&&(u.scroll_id=s),i!==void 0&&(u.votes=i),o&&(u.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(u),signal:we(be,a)});return Ae(p,Se)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:yt})}function xK(e){return reactQuery.queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function $d(e){let r=await _()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function CK(e,t){let r=e?.replace("@","");return reactQuery.queryOptions({queryKey:c.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return $d(t)},enabled:!!r&&!!t})}async function zd(e,t){let n=await _()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Jd(e,t,r){return e.setQueryData(c.support.settings(t),r),e.invalidateQueries({queryKey:c.support.settings(t)})}function IK(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return zd(t,i)},onSuccess(i){n&&Jd(r,n,i);}})}function NK(e){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function UK(e){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function $K(e,t){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function JK(e){return reactQuery.queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function eB(e,t){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function iB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[Ur(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function cB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Vr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function lB(e){let r=await _()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var nf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function gB(){return reactQuery.queryOptions({queryKey:c.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(nf,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` +`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var hB=1.1,of=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(of||{});function _B(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function cf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let u=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:u?{total_votes:u.total_votes??0,hive_hp:u.hive_hp,hive_proxied_hp:u.hive_proxied_hp,hive_hp_incl_proxied:u.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function PB(e,t){return reactQuery.queryOptions({queryKey:c.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:reactQuery.isServer?Jn:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return cf(o[0])}})}function EB(e,t,r){return v(c.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** * @license bytebuffer.ts (c) 2015 Daniel Wirtz * Backing buffer: ArrayBuffer, Accessor: DataView * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bytebuffer.ts for details * modified by @xmcl/bytebuffer * And customized for hive-tx - */exports.ACCOUNT_OPERATION_GROUPS=ni;exports.ALL_ACCOUNT_OPERATIONS=Oa;exports.ALL_NOTIFY_TYPES=Gi;exports.AssetOperation=td;exports.BROADCAST_INCLUSION_DELAY_MS=Om;exports.BuySellTransactionType=xi;exports.CONFIG=d;exports.EcencyAnalytics=We;exports.ErrorType=Vn;exports.HIVE_ACCOUNT_OPERATION_GROUPS=Wr;exports.HIVE_OPERATION_LIST=uT;exports.HIVE_OPERATION_NAME_BY_ID=dT;exports.HIVE_OPERATION_ORDERS=lT;exports.HiveEngineToken=Ut;exports.HiveSignerIntegration=ji;exports.HiveTxTransaction=Te;exports.INTERNAL_API_TIMEOUT_MS=_e;exports.MAX_SEARCH_QUERY_LENGTH=cD;exports.MAX_SEARCH_TAGS=uD;exports.Memo=Nn;exports.NaiMap=St;exports.NotificationFilter=Up;exports.NotificationViewType=jp;exports.NotifyTypes=Vp;exports.OPERATION_AUTHORITY_MAP=Tc;exports.OrderIdPrefix=Ei;exports.POLLS_PROTOCOL_VERSION=LK;exports.PointTransactionType=ud;exports.PollPreferredInterpretation=Vd;exports.PrivateKey=H;exports.PublicKey=J;exports.QUEST_CATALOG=xp;exports.QUEST_MIN_CONTENT_LENGTH=Ep;exports.QueryKeys=u;exports.ROLES=Np;exports.SERVER_GC_TIME_MS=$n;exports.SIMILAR_ENTRIES_MIN_RENDER=RD;exports.STREAK_FREEZE_MAX_OWNED=vE;exports.STREAK_FREEZE_PRICE=bE;exports.SUBSCRIBERS_PAGE_SIZE=$i;exports.SearchQuery=ho;exports.SearchType=wo;exports.Signature=Ae;exports.SortOrder=mi;exports.Symbol=Wn;exports.THREESPEAK_BENEFICIARY_ACCOUNT=Kt;exports.THREESPEAK_BENEFICIARY_WEIGHT=hx;exports.ThreeSpeakIntegration=Kx;exports.accountNameByteLength=ra;exports.addDraft=Ki;exports.addImage=qi;exports.addOptimisticDiscussionEntry=SO;exports.addSchedule=Ni;exports.applySupportSettingsUpdate=Dd;exports.applyVoteCacheUpdate=tp;exports.bridgeApiCall=se;exports.broadcastJson=Ln;exports.broadcastOperations=Z;exports.broadcastOperationsAsync=Hn;exports.buildAccountCreateOp=Ir;exports.buildAccountUpdate2Op=Xu;exports.buildAccountUpdateOp=Yu;exports.buildActiveCustomJsonOp=ic;exports.buildBoostPlusOp=Mr;exports.buildCancelTransferFromSavingsOp=Oi;exports.buildChangeRecoveryAccountOp=ec;exports.buildClaimAccountOp=Kr;exports.buildClaimInterestOps=it;exports.buildClaimRewardBalanceOp=qr;exports.buildCollateralizedConvertOp=hr;exports.buildCommentOp=Ie;exports.buildCommentOptionsOp=De;exports.buildCommunityRegistrationOp=Hr;exports.buildConvertOp=ct;exports.buildCreateClaimedAccountOp=Dr;exports.buildDelegateRcOp=_r;exports.buildDelegateVestingSharesOp=at;exports.buildDeleteCommentOp=gr;exports.buildEngineClaimOp=wr;exports.buildEngineOp=Me;exports.buildFlagPostOp=zu;exports.buildFollowOp=br;exports.buildGrantPostingPermissionOp=Br;exports.buildIgnoreOp=ju;exports.buildLimitOrderCancelOp=Fr;exports.buildLimitOrderCreateOp=qt;exports.buildLimitOrderCreateOpWithType=Ju;exports.buildMultiPointTransferOps=nc;exports.buildMultiTransferOps=Uu;exports.buildMutePostOp=Rr;exports.buildMuteUserOp=Gu;exports.buildPinPostOp=Tr;exports.buildPointTransferOp=$e;exports.buildPostingCustomJsonOp=oc;exports.buildPostingJsonMetadata=ei;exports.buildProfileMetadata=lr;exports.buildPromoteOp=Qr;exports.buildProposalCreateOp=Or;exports.buildProposalVoteOp=xr;exports.buildRcDelegationOp=Nr;exports.buildReblogOp=yr;exports.buildRecoverAccountOp=rc;exports.buildRecurrentTransferOp=Vu;exports.buildRemoveProposalOp=$u;exports.buildRequestAccountRecoveryOp=tc;exports.buildRevokeKeysOp=ki;exports.buildRevokePostingPermissionOp=Zu;exports.buildSearchQuery=pD;exports.buildSetLastReadOps=vr;exports.buildSetRoleOp=kr;exports.buildSetWithdrawVestingRouteOp=ut;exports.buildSubscribeOp=Er;exports.buildTransferFromSavingsOp=Be;exports.buildTransferOp=Ke;exports.buildTransferToSavingsOp=Le;exports.buildTransferToVestingOp=ot;exports.buildUnfollowOp=Rt;exports.buildUnignoreOp=Lu;exports.buildUnsubscribeOp=Sr;exports.buildUpdateCommunityOp=Cr;exports.buildUpdateProposalOp=Wu;exports.buildVoteOp=mr;exports.buildWithdrawVestingOp=st;exports.buildWitnessProxyOp=Pr;exports.buildWitnessVoteOp=Ar;exports.buyStreakFreezeRequest=Rp;exports.calculateRCMana=xt;exports.calculateVPMana=ur;exports.callREST=ee;exports.callRPC=g;exports.callRPCBroadcast=Qe;exports.callWithQuorum=Pt;exports.canRevokeFromAuthority=zA;exports.checkFavoriteQueryOptions=$y;exports.checkUsernameWalletsPendingQueryOptions=Py;exports.claimPointsRequest=pd;exports.collectRequestedOperations=Gr;exports.decodeObj=Nm;exports.dedupeAndSortKeyAuths=dc;exports.deleteDraft=Mi;exports.deleteImage=Di;exports.deleteSchedule=Qi;exports.downVotingPower=_P;exports.earnsQuestContentCredit=_E;exports.encodeObj=Mm;exports.enforceThreeSpeakBeneficiary=wx;exports.estimateRcPrecheck=nE;exports.extractAccountProfile=Xn;exports.formatError=Os;exports.formattedNumber=ze;exports.getAccountDelegationsQueryOptions=Jk;exports.getAccountFullQueryOptions=M;exports.getAccountNotificationsInfiniteQueryOptions=SS;exports.getAccountPendingRecoveryQueryOptions=th;exports.getAccountPosts=dr;exports.getAccountPostsInfiniteQueryOptions=a_;exports.getAccountPostsQueryOptions=u_;exports.getAccountRcQueryOptions=eE;exports.getAccountRecoveriesQueryOptions=Jy;exports.getAccountReputationsQueryOptions=ah;exports.getAccountSubscriptionsQueryOptions=Fy;exports.getAccountVoteHistoryInfiniteQueryOptions=iv;exports.getAccountWalletAssetInfoQueryOptions=YF;exports.getAccountsQueryOptions=Ug;exports.getAggregatedBalanceQueryOptions=bv;exports.getAiAssistPriceQueryOptions=pg;exports.getAiGeneratePriceQueryOptions=sg;exports.getAiTranscribePriceQueryOptions=mg;exports.getAllHiveEngineTokensQueryOptions=uo;exports.getAnnouncementsQueryOptions=tk;exports.getBadActorsQueryOptions=VK;exports.getBalanceHistoryInfiniteQueryOptions=gv;exports.getBookmarksInfiniteQueryOptions=By;exports.getBookmarksQueryOptions=Ky;exports.getBoostPlusAccountPricesQueryOptions=kK;exports.getBoostPlusPricesQueryOptions=dK;exports.getBotsQueryOptions=_h;exports.getBoundFetch=w;exports.getChainPropertiesQueryOptions=NP;exports.getCollateralizedConversionRequestsQueryOptions=uC;exports.getCommentHistoryQueryOptions=W_;exports.getCommunities=jw;exports.getCommunitiesQueryOptions=iS;exports.getCommunity=li;exports.getCommunityContextQueryOptions=cS;exports.getCommunityPermissions=KS;exports.getCommunityQueryOptions=mS;exports.getCommunitySubscribersInfiniteQueryOptions=vS;exports.getCommunitySubscribersQueryOptions=bS;exports.getCommunityType=DS;exports.getContentQueryOptions=ww;exports.getContentRepliesQueryOptions=Pw;exports.getControversialRisingInfiniteQueryOptions=vD;exports.getConversionRequestsQueryOptions=iC;exports.getCurrencyRate=no;exports.getCurrencyRates=KR;exports.getCurrencyTokenRate=DR;exports.getCurrentMedianHistoryPriceQueryOptions=PR;exports.getCustomJsonAuthority=Rc;exports.getDeletedEntryQueryOptions=Y_;exports.getDiscoverCurationQueryOptions=ax;exports.getDiscoverLeaderboardQueryOptions=rx;exports.getDiscussion=pi;exports.getDiscussionQueryOptions=e_;exports.getDiscussionsQueryOptions=gi;exports.getDraftsInfiniteQueryOptions=B_;exports.getDraftsQueryOptions=K_;exports.getDynamicPropsQueryOptions=be;exports.getEntryActiveVotesQueryOptions=uw;exports.getFavoritesInfiniteQueryOptions=Uy;exports.getFavoritesQueryOptions=Hy;exports.getFeedHistoryQueryOptions=_R;exports.getFollowCountQueryOptions=Wg;exports.getFollowersQueryOptions=Xg;exports.getFollowingQueryOptions=ny;exports.getFragmentsInfiniteQueryOptions=Zh;exports.getFragmentsQueryOptions=je;exports.getFriendsInfiniteQueryOptions=qh;exports.getGalleryImagesQueryOptions=U_;exports.getGameStatusCheckQueryOptions=aE;exports.getHbdAssetGeneralInfoQueryOptions=Yi;exports.getHbdAssetTransactionsQueryOptions=PT;exports.getHiveAssetGeneralInfoQueryOptions=Bt;exports.getHiveAssetMetricQueryOptions=FT;exports.getHiveAssetTransactionsQueryOptions=Mt;exports.getHiveAssetWithdrawalRoutesQueryOptions=KT;exports.getHiveEngineBalancesWithUsdQueryOptions=vF;exports.getHiveEngineMetrics=Hl;exports.getHiveEngineOpenOrders=UR;exports.getHiveEngineOrderBook=QR;exports.getHiveEngineTokenGeneralInfoQueryOptions=co;exports.getHiveEngineTokenMetrics=oo;exports.getHiveEngineTokenTransactions=io;exports.getHiveEngineTokenTransactionsQueryOptions=rF;exports.getHiveEngineTokensBalances=Nt;exports.getHiveEngineTokensBalancesQueryOptions=Ht;exports.getHiveEngineTokensMarket=Ge;exports.getHiveEngineTokensMarketQueryOptions=zR;exports.getHiveEngineTokensMetadata=Qt;exports.getHiveEngineTokensMetadataQueryOptions=ao;exports.getHiveEngineTokensMetricsQueryOptions=sF;exports.getHiveEngineTradeHistory=HR;exports.getHiveEngineUnclaimedRewards=so;exports.getHiveEngineUnclaimedRewardsQueryOptions=pF;exports.getHiveHbdStatsQueryOptions=aR;exports.getHivePoshLinksQueryOptions=Ux;exports.getHivePowerAssetGeneralInfoQueryOptions=Xi;exports.getHivePowerAssetTransactionsQueryOptions=kT;exports.getHivePowerDelegatesInfiniteQueryOptions=QT;exports.getHivePowerDelegatingsQueryOptions=LT;exports.getHivePrice=BR;exports.getImagesInfiniteQueryOptions=V_;exports.getImagesQueryOptions=H_;exports.getIncomingRcQueryOptions=CC;exports.getMarketData=IR;exports.getMarketDataQueryOptions=lR;exports.getMarketHistoryQueryOptions=nR;exports.getMarketStatisticsQueryOptions=ZT;exports.getMutedUsersQueryOptions=uy;exports.getNextAccountHistoryPageParam=Al;exports.getNormalizePostQueryOptions=Jb;exports.getNotificationSetting=m0;exports.getNotifications=d0;exports.getNotificationsInfiniteQueryOptions=jS;exports.getNotificationsSettingsQueryOptions=YS;exports.getNotificationsUnreadCountQueryOptions=QS;exports.getOpenOrdersQueryOptions=bC;exports.getOperationAuthority=qc;exports.getOrderBookQueryOptions=zT;exports.getOutgoingRcDelegationsInfiniteQueryOptions=xC;exports.getPageStatsQueryOptions=lx;exports.getPointsAssetGeneralInfoQueryOptions=po;exports.getPointsAssetTransactionsQueryOptions=NF;exports.getPointsQueryOptions=dt;exports.getPollQueryOptions=YK;exports.getPortfolioQueryOptions=Ji;exports.getPost=Wa;exports.getPostHeader=Vw;exports.getPostHeaderQueryOptions=kw;exports.getPostQueryOptions=si;exports.getPostTipsQueryOptions=tb;exports.getPostsRanked=ci;exports.getPostsRankedInfiniteQueryOptions=y_;exports.getPostsRankedQueryOptions=h_;exports.getProMembersQueryOptions=Ov;exports.getProfiles=Tt;exports.getProfilesQueryOptions=cv;exports.getPromotePriceQueryOptions=OK;exports.getPromotedPost=y0;exports.getPromotedPostsQuery=nw;exports.getProposalAuthority=Fc;exports.getProposalQueryOptions=bk;exports.getProposalVotesInfiniteQueryOptions=Tk;exports.getProposalsQueryOptions=Ok;exports.getQueryClient=b;exports.getQuestCatalogEntry=wE;exports.getQuestsQueryOptions=yE;exports.getRcDelegationActiveQueryOptions=bK;exports.getRcDelegationPricesQueryOptions=yK;exports.getRcStatsQueryOptions=Jx;exports.getRebloggedByQueryOptions=S_;exports.getReblogsQueryOptions=A_;exports.getReceivedVestingSharesQueryOptions=qC;exports.getRecurrentTransfersQueryOptions=BC;exports.getReferralsInfiniteQueryOptions=Ph;exports.getReferralsStatsQueryOptions=Sh;exports.getRelationshipBetweenAccounts=Ww;exports.getRelationshipBetweenAccountsQueryOptions=ri;exports.getRequiredAuthority=PP;exports.getRewardFundQueryOptions=tg;exports.getRewardedCommunitiesQueryOptions=RS;exports.getSavingsWithdrawFromQueryOptions=dC;exports.getSchedulesInfiniteQueryOptions=F_;exports.getSchedulesQueryOptions=R_;exports.getSearchAccountQueryOptions=MD;exports.getSearchAccountsByUsernameQueryOptions=_y;exports.getSearchApiInfiniteQueryOptions=zD;exports.getSearchFriendsQueryOptions=Mh;exports.getSearchPathQueryOptions=ZD;exports.getSearchTopicsQueryOptions=VD;exports.getShortsFeedQueryOptions=gb;exports.getSimilarEntriesQueryOptions=FD;exports.getSpotlightsQueryOptions=ok;exports.getStatsQueryOptions=$x;exports.getSubscribers=$w;exports.getSubscriptions=Lw;exports.getSupportSettingsQueryOptions=nK;exports.getSupportSettingsRequest=Rd;exports.getTradeHistoryQueryOptions=gR;exports.getTransactionsInfiniteQueryOptions=gh;exports.getTrendingTagsQueryOptions=Vh;exports.getTrendingTagsWithStatsQueryOptions=zh;exports.getUserPostVoteQueryOptions=fw;exports.getUserProposalVotesQueryOptions=Ik;exports.getVestingDelegationExpirationsQueryOptions=eC;exports.getVestingDelegationsQueryOptions=$k;exports.getVisibleFirstLevelThreadItems=_i;exports.getWavesByAccountQueryOptions=Hb;exports.getWavesByHostQueryOptions=Ab;exports.getWavesByTagQueryOptions=Sb;exports.getWavesFeedQueryOptions=cb;exports.getWavesFollowingQueryOptions=Fb;exports.getWavesLatestFeedQueryOptions=pb;exports.getWavesTrendingAuthorsQueryOptions=Lb;exports.getWavesTrendingTagsQueryOptions=Kb;exports.getWithdrawRoutesQueryOptions=yC;exports.getWitnessVoterCountQueryOptions=ZI;exports.getWitnessVotersPageQueryOptions=XI;exports.getWitnessesInfiniteQueryOptions=YI;exports.hasThreeSpeakEmbed=lp;exports.hiveTxConfig=x;exports.hiveTxUtils=re;exports.hsTokenRenew=NK;exports.invalidateAfterBroadcast=S;exports.isCommunity=Gn;exports.isEmptyDate=zn;exports.isInfoError=Es;exports.isNetworkError=Ss;exports.isQueryableAccountName=Ve;exports.isResourceCreditsError=xs;exports.isThreeSpeakBeneficiary=_x;exports.isVoteAlreadyReflected=ep;exports.isWif=Qn;exports.isWrappedResponse=Ns;exports.lookupAccountsQueryOptions=my;exports.makeQueryClient=Km;exports.mapMetaChoicesToPollChoices=$K;exports.mapThreadItemsToWaveEntries=bi;exports.markNotifications=Fi;exports.measureQuestContentLength=Sp;exports.moveSchedule=Hi;exports.normalizePost=di;exports.normalizeSearchAuthor=ld;exports.normalizeSearchCategory=dd;exports.normalizeSearchTags=fd;exports.normalizeToWrappedResponse=oe;exports.normalizeWaveEntryFromApi=me;exports.onboardEmail=h0;exports.parseAccounts=Ct;exports.parseAsset=C;exports.parseChainError=He;exports.parsePostingMetadataRoot=ta;exports.parseProfileMetadata=qe;exports.pickRicherMetadataSnapshot=Zn;exports.powerRechargeTime=wP;exports.proMembersSet=xv;exports.rcPower=bP;exports.removeOptimisticDiscussionEntry=Ui;exports.resolveAccountHistoryLimit=Pl;exports.resolveHiveOperationFilters=pt;exports.resolvePost=ai;exports.restoreDiscussionSnapshots=Vi;exports.restoreEntryInCache=CO;exports.roleMap=qS;exports.saveNotificationSetting=f0;exports.search=xD;exports.searchPath=ED;exports.searchQueryOptions=bD;exports.sha256=um;exports.shouldTriggerAuthFallback=ye;exports.signUp=c0;exports.similar=bo;exports.sortDiscussions=Ga;exports.subscribeEmail=p0;exports.toEntryArray=mu;exports.updateDraft=Bi;exports.updateEntryInCache=kO;exports.updateSupportSettingsRequest=Id;exports.uploadImage=Ii;exports.uploadImageWithSignature=g0;exports.useAccountFavoriteAdd=_A;exports.useAccountFavoriteDelete=OA;exports.useAccountRelationsUpdate=Kv;exports.useAccountRevokeKey=tP;exports.useAccountRevokePosting=QA;exports.useAccountUpdate=Rv;exports.useAccountUpdateKeyAuths=Si;exports.useAccountUpdatePassword=IA;exports.useAccountUpdateRecovery=WA;exports.useAddDraft=A0;exports.useAddFragment=WP;exports.useAddImage=Z0;exports.useAddSchedule=M0;exports.useAiAssist=Ag;exports.useAiTranscribe=Eg;exports.useBookmarkAdd=lA;exports.useBookmarkDelete=gA;exports.useBoostPlus=FK;exports.useBroadcastMutation=v;exports.useBuyStreakFreeze=xE;exports.useClaimAccount=oP;exports.useClaimEngineRewards=PI;exports.useClaimInterest=Xq;exports.useClaimPoints=sD;exports.useClaimRewards=nI;exports.useComment=OO;exports.useConvert=Wq;exports.useCreateAccount=fP;exports.useCrossPost=MO;exports.useDelegateEngineToken=aI;exports.useDelegateRc=BI;exports.useDelegateVestingShares=fq;exports.useDeleteComment=IO;exports.useDeleteDraft=q0;exports.useDeleteImage=iO;exports.useDeleteSchedule=V0;exports.useEditFragment=e0;exports.useEngineMarketOrder=SI;exports.useFollow=nA;exports.useGameClaim=dE;exports.useGenerateImage=wg;exports.useGrantPostingPermission=cP;exports.useLimitOrderCancel=RR;exports.useLimitOrderCreate=SR;exports.useMarkNotificationsRead=dk;exports.useMoveSchedule=G0;exports.useMutePost=BE;exports.usePinPost=ZE;exports.usePollVote=eB;exports.usePromote=$O;exports.useProposalCreate=Uk;exports.useProposalVote=Mk;exports.useRcDelegation=KK;exports.useReblog=bO;exports.useRecordActivity=Vr;exports.useRegisterCommunityRewards=zE;exports.useRemoveFragment=s0;exports.useSetCommunityRole=HE;exports.useSetLastRead=yk;exports.useSetWithdrawVestingRoute=wq;exports.useSignOperationByHivesigner=DP;exports.useSignOperationByKey=kP;exports.useSignOperationByKeychain=RP;exports.useStakeEngineToken=gI;exports.useSubscribeCommunity=CE;exports.useTransfer=nq;exports.useTransferEngineToken=Aq;exports.useTransferFromSavings=Fq;exports.useTransferPoint=uq;exports.useTransferToSavings=Sq;exports.useTransferToVesting=Bq;exports.useUndelegateEngineToken=lI;exports.useUnfollow=aA;exports.useUnstakeEngineToken=_I;exports.useUnsubscribeCommunity=qE;exports.useUpdateCommunity=LE;exports.useUpdateDraft=S0;exports.useUpdateReply=UO;exports.useUpdateSupportSettings=uK;exports.useUploadImage=uO;exports.useVote=gO;exports.useWalletOperation=qI;exports.useWithdrawVesting=Uq;exports.useWitnessProxy=LI;exports.useWitnessVote=HI;exports.usrActivity=l0;exports.validatePostCreating=op;exports.verifyPostOnAlternateNode=oi;exports.vestsToHp=Ue;exports.votingPower=hP;exports.votingRshares=Cc;exports.votingValue=vP;exports.withTimeoutSignal=we;//# sourceMappingURL=index.cjs.map + */exports.ACCOUNT_OPERATION_GROUPS=ai;exports.ALL_ACCOUNT_OPERATIONS=Ca;exports.ALL_NOTIFY_TYPES=Zi;exports.AssetOperation=yd;exports.BROADCAST_INCLUSION_DELAY_MS=Mm;exports.BuySellTransactionType=Ci;exports.CONFIG=d;exports.EcencyAnalytics=ze;exports.ErrorType=Wn;exports.HIVE_ACCOUNT_OPERATION_GROUPS=Yr;exports.HIVE_OPERATION_LIST=IT;exports.HIVE_OPERATION_NAME_BY_ID=NT;exports.HIVE_OPERATION_ORDERS=BT;exports.HiveEngineToken=Lt;exports.HiveSignerIntegration=Gi;exports.HiveTxTransaction=Re;exports.INTERNAL_API_TIMEOUT_MS=be;exports.MAX_SEARCH_QUERY_LENGTH=DD;exports.MAX_SEARCH_TAGS=ID;exports.Memo=Vn;exports.NaiMap=Tt;exports.NotificationFilter=nl;exports.NotificationViewType=ol;exports.NotifyTypes=il;exports.OPERATION_AUTHORITY_MAP=Du;exports.OrderIdPrefix=Ti;exports.POLLS_PROTOCOL_VERSION=hB;exports.PointTransactionType=Pd;exports.PollPreferredInterpretation=of;exports.PrivateKey=H;exports.PublicKey=J;exports.QUEST_CATALOG=Qp;exports.QUEST_MIN_CONTENT_LENGTH=Hp;exports.QueryKeys=c;exports.RC_RESOURCE_NAMES=zi;exports.ROLES=el;exports.SERVER_GC_TIME_MS=Jn;exports.SIMILAR_ENTRIES_MIN_RENDER=nK;exports.STREAK_FREEZE_MAX_OWNED=WE;exports.STREAK_FREEZE_PRICE=$E;exports.SUBSCRIBERS_PAGE_SIZE=Yi;exports.SearchQuery=Ao;exports.SearchType=Po;exports.Signature=Pe;exports.SortOrder=_i;exports.Symbol=Yn;exports.THREESPEAK_BENEFICIARY_ACCOUNT=Mt;exports.THREESPEAK_BENEFICIARY_WEIGHT=qx;exports.ThreeSpeakIntegration=Xx;exports.accountNameByteLength=aa;exports.addDraft=Qi;exports.addImage=Bi;exports.addOptimisticDiscussionEntry=VO;exports.addSchedule=Vi;exports.applySupportSettingsUpdate=Jd;exports.applyVoteCacheUpdate=sp;exports.bridgeApiCall=se;exports.broadcastJson=zn;exports.broadcastOperations=Z;exports.broadcastOperationsAsync=Ln;exports.buildAccountCreateOp=Nr;exports.buildAccountUpdate2Op=nu;exports.buildAccountUpdateOp=ru;exports.buildActiveCustomJsonOp=uu;exports.buildBoostPlusOp=Ur;exports.buildCancelTransferFromSavingsOp=ki;exports.buildChangeRecoveryAccountOp=ou;exports.buildClaimAccountOp=Qr;exports.buildClaimInterestOps=at;exports.buildClaimRewardBalanceOp=Br;exports.buildCollateralizedConvertOp=vr;exports.buildCommentOp=De;exports.buildCommentOptionsOp=Ke;exports.buildCommunityRegistrationOp=Lr;exports.buildConvertOp=dt;exports.buildCreateClaimedAccountOp=Mr;exports.buildDelegateRcOp=Pr;exports.buildDelegateVestingSharesOp=pt;exports.buildDeleteCommentOp=wr;exports.buildEngineClaimOp=Ar;exports.buildEngineOp=Me;exports.buildFlagPostOp=eu;exports.buildFollowOp=Or;exports.buildGrantPostingPermissionOp=Hr;exports.buildIgnoreOp=zc;exports.buildLimitOrderCancelOp=Kr;exports.buildLimitOrderCreateOp=Kt;exports.buildLimitOrderCreateOpWithType=tu;exports.buildMultiPointTransferOps=cu;exports.buildMultiTransferOps=Wc;exports.buildMutePostOp=Dr;exports.buildMuteUserOp=Zc;exports.buildPinPostOp=Ir;exports.buildPointTransferOp=Ge;exports.buildPostingCustomJsonOp=pu;exports.buildPostingJsonMetadata=ii;exports.buildProfileMetadata=gr;exports.buildPromoteOp=jr;exports.buildProposalCreateOp=kr;exports.buildProposalVoteOp=Cr;exports.buildRcDelegationOp=Vr;exports.buildReblogOp=br;exports.buildRecoverAccountOp=au;exports.buildRecurrentTransferOp=Gc;exports.buildRemoveProposalOp=Yc;exports.buildRequestAccountRecoveryOp=su;exports.buildRevokeKeysOp=Fi;exports.buildRevokePostingPermissionOp=iu;exports.buildSearchQuery=KD;exports.buildSetLastReadOps=xr;exports.buildSetRoleOp=Fr;exports.buildSetWithdrawVestingRouteOp=lt;exports.buildSubscribeOp=Tr;exports.buildTransferFromSavingsOp=Ne;exports.buildTransferOp=Be;exports.buildTransferToSavingsOp=We;exports.buildTransferToVestingOp=ct;exports.buildUnfollowOp=It;exports.buildUnignoreOp=Jc;exports.buildUnsubscribeOp=Rr;exports.buildUpdateCommunityOp=qr;exports.buildUpdateProposalOp=Xc;exports.buildVoteOp=_r;exports.buildWithdrawVestingOp=ut;exports.buildWitnessProxyOp=Sr;exports.buildWitnessVoteOp=Er;exports.buyStreakFreezeRequest=$p;exports.calculateRCMana=kt;exports.calculateVPMana=lr;exports.callREST=ee;exports.callRPC=g;exports.callRPCBroadcast=He;exports.callWithQuorum=Et;exports.canRevokeFromAuthority=lP;exports.checkFavoriteQueryOptions=ch;exports.checkUsernameWalletsPendingQueryOptions=My;exports.claimPointsRequest=xd;exports.collectRequestedOperations=Xr;exports.computeResourceCost=Rp;exports.countCommentResourceUsage=Fp;exports.decodeObj=eg;exports.dedupeAndSortKeyAuths=hu;exports.deleteDraft=Ui;exports.deleteImage=Mi;exports.deleteSchedule=ji;exports.downVotingPower=DP;exports.earnsQuestContentCredit=LE;exports.encodeObj=Zm;exports.enforceThreeSpeakBeneficiary=Ix;exports.estimateCommentRcCost=CE;exports.estimateCommentTransactionBytes=Dp;exports.estimateRcPrecheck=xE;exports.extractAccountProfile=ri;exports.formatError=Cs;exports.formattedNumber=Xe;exports.getAccountDelegationsQueryOptions=AC;exports.getAccountFullQueryOptions=N;exports.getAccountNotificationsInfiniteQueryOptions=ZS;exports.getAccountPendingRecoveryQueryOptions=hh;exports.getAccountPosts=yr;exports.getAccountPostsInfiniteQueryOptions=Pw;exports.getAccountPostsQueryOptions=Ow;exports.getAccountRcQueryOptions=yE;exports.getAccountRecoveriesQueryOptions=dh;exports.getAccountReputationsQueryOptions=Ph;exports.getAccountSubscriptionsQueryOptions=Gy;exports.getAccountVoteHistoryInfiniteQueryOptions=bv;exports.getAccountWalletAssetInfoQueryOptions=Pq;exports.getAccountsQueryOptions=iy;exports.getAggregatedBalanceQueryOptions=Kv;exports.getAiAssistPriceQueryOptions=Eg;exports.getAiGeneratePriceQueryOptions=Ag;exports.getAiTranscribePriceQueryOptions=Tg;exports.getAllHiveEngineTokensQueryOptions=mo;exports.getAnnouncementsQueryOptions=Sk;exports.getBadActorsQueryOptions=gB;exports.getBalanceHistoryInfiniteQueryOptions=Rv;exports.getBookmarksInfiniteQueryOptions=Zy;exports.getBookmarksQueryOptions=Xy;exports.getBoostPlusAccountPricesQueryOptions=eB;exports.getBoostPlusPricesQueryOptions=NK;exports.getBotsQueryOptions=Dh;exports.getBoundFetch=_;exports.getChainPropertiesQueryOptions=t0;exports.getCollateralizedConversionRequestsQueryOptions=IC;exports.getCommentHistoryQueryOptions=ub;exports.getCommunities=sw;exports.getCommunitiesQueryOptions=TS;exports.getCommunity=gi;exports.getCommunityContextQueryOptions=DS;exports.getCommunityPermissions=ck;exports.getCommunityQueryOptions=QS;exports.getCommunitySubscribersInfiniteQueryOptions=WS;exports.getCommunitySubscribersQueryOptions=$S;exports.getCommunityType=ak;exports.getContentQueryOptions=I_;exports.getContentRepliesQueryOptions=M_;exports.getControversialRisingInfiniteQueryOptions=WD;exports.getConversionRequestsQueryOptions=TC;exports.getCurrencyRate=co;exports.getCurrencyRates=cF;exports.getCurrencyTokenRate=aF;exports.getCurrentMedianHistoryPriceQueryOptions=zR;exports.getCustomJsonAuthority=Ku;exports.getDeletedEntryQueryOptions=fb;exports.getDiscoverCurationQueryOptions=Px;exports.getDiscoverLeaderboardQueryOptions=_x;exports.getDiscussion=mi;exports.getDiscussionQueryOptions=yw;exports.getDiscussionsQueryOptions=wi;exports.getDraftsInfiniteQueryOptions=Zw;exports.getDraftsQueryOptions=Xw;exports.getDynamicPropsQueryOptions=ve;exports.getEntryActiveVotesQueryOptions=O_;exports.getFavoritesInfiniteQueryOptions=ih;exports.getFavoritesQueryOptions=nh;exports.getFeedHistoryQueryOptions=LR;exports.getFollowCountQueryOptions=uy;exports.getFollowersQueryOptions=my;exports.getFollowingQueryOptions=wy;exports.getFragmentsInfiniteQueryOptions=g_;exports.getFragmentsQueryOptions=$e;exports.getFriendsInfiniteQueryOptions=zh;exports.getGalleryImagesQueryOptions=ib;exports.getGameStatusCheckQueryOptions=qE;exports.getHbdAssetGeneralInfoQueryOptions=ro;exports.getHbdAssetTransactionsQueryOptions=zT;exports.getHiveAssetGeneralInfoQueryOptions=Qt;exports.getHiveAssetMetricQueryOptions=iR;exports.getHiveAssetTransactionsQueryOptions=Ht;exports.getHiveAssetWithdrawalRoutesQueryOptions=cR;exports.getHiveEngineBalancesWithUsdQueryOptions=WF;exports.getHiveEngineMetrics=rd;exports.getHiveEngineOpenOrders=mF;exports.getHiveEngineOrderBook=dF;exports.getHiveEngineTokenGeneralInfoQueryOptions=go;exports.getHiveEngineTokenMetrics=po;exports.getHiveEngineTokenTransactions=uo;exports.getHiveEngineTokenTransactionsQueryOptions=kF;exports.getHiveEngineTokensBalances=Ut;exports.getHiveEngineTokensBalancesQueryOptions=jt;exports.getHiveEngineTokensMarket=Ye;exports.getHiveEngineTokensMarketQueryOptions=vF;exports.getHiveEngineTokensMetadata=Vt;exports.getHiveEngineTokensMetadataQueryOptions=fo;exports.getHiveEngineTokensMetricsQueryOptions=FF;exports.getHiveEngineTradeHistory=fF;exports.getHiveEngineUnclaimedRewards=lo;exports.getHiveEngineUnclaimedRewardsQueryOptions=KF;exports.getHiveHbdStatsQueryOptions=qR;exports.getHivePoshLinksQueryOptions=iE;exports.getHivePowerAssetGeneralInfoQueryOptions=no;exports.getHivePowerAssetTransactionsQueryOptions=eR;exports.getHivePowerDelegatesInfiniteQueryOptions=dR;exports.getHivePowerDelegatingsQueryOptions=hR;exports.getHivePrice=uF;exports.getImagesInfiniteQueryOptions=ob;exports.getImagesQueryOptions=nb;exports.getIncomingRcQueryOptions=tT;exports.getMarketData=sF;exports.getMarketDataQueryOptions=BR;exports.getMarketHistoryQueryOptions=CR;exports.getMarketStatisticsQueryOptions=xR;exports.getMutedUsersQueryOptions=Oy;exports.getNextAccountHistoryPageParam=Bl;exports.getNormalizePostQueryOptions=dv;exports.getNotificationSetting=T0;exports.getNotifications=k0;exports.getNotificationsInfiniteQueryOptions=yk;exports.getNotificationsSettingsQueryOptions=Pk;exports.getNotificationsUnreadCountQueryOptions=dk;exports.getOpenOrdersQueryOptions=$C;exports.getOperationAuthority=Nu;exports.getOrderBookQueryOptions=vR;exports.getOutgoingRcDelegationsInfiniteQueryOptions=YC;exports.getPageStatsQueryOptions=Sx;exports.getPointsAssetGeneralInfoQueryOptions=yo;exports.getPointsAssetTransactionsQueryOptions=lq;exports.getPointsQueryOptions=gt;exports.getPollQueryOptions=PB;exports.getPortfolioQueryOptions=to;exports.getPost=Xa;exports.getPostHeader=ow;exports.getPostHeaderQueryOptions=j_;exports.getPostQueryOptions=pi;exports.getPostTipsQueryOptions=hb;exports.getPostsRanked=fi;exports.getPostsRankedInfiniteQueryOptions=Fw;exports.getPostsRankedQueryOptions=qw;exports.getProMembersQueryOptions=Qv;exports.getProfiles=qt;exports.getProfilesQueryOptions=xv;exports.getPromotePriceQueryOptions=JK;exports.getPromotedPost=F0;exports.getPromotedPostsQuery=w_;exports.getProposalAuthority=Bu;exports.getProposalQueryOptions=$k;exports.getProposalVotesInfiniteQueryOptions=rC;exports.getProposalsQueryOptions=Jk;exports.getQueryClient=b;exports.getQuestCatalogEntry=jE;exports.getQuestsQueryOptions=UE;exports.getRcDelegationActiveQueryOptions=$K;exports.getRcDelegationPricesQueryOptions=UK;exports.getRcResourceParamsQueryOptions=vE;exports.getRcStatsQueryOptions=dE;exports.getRebloggedByQueryOptions=Vw;exports.getReblogsQueryOptions=Nw;exports.getReceivedVestingSharesQueryOptions=oT;exports.getRecurrentTransfersQueryOptions=uT;exports.getReferralsInfiniteQueryOptions=Mh;exports.getReferralsStatsQueryOptions=Vh;exports.getRelationshipBetweenAccounts=uw;exports.getRelationshipBetweenAccountsQueryOptions=si;exports.getRequiredAuthority=MP;exports.getRewardFundQueryOptions=yg;exports.getRewardedCommunitiesQueryOptions=nk;exports.getSavingsWithdrawFromQueryOptions=NC;exports.getSchedulesInfiniteQueryOptions=Gw;exports.getSchedulesQueryOptions=Ww;exports.getSearchAccountQueryOptions=pK;exports.getSearchAccountsByUsernameQueryOptions=Dy;exports.getSearchApiInfiniteQueryOptions=vK;exports.getSearchFriendsQueryOptions=e_;exports.getSearchPathQueryOptions=xK;exports.getSearchTopicsQueryOptions=gK;exports.getShortsFeedQueryOptions=Rb;exports.getSimilarEntriesQueryOptions=iK;exports.getSpotlightsQueryOptions=Rk;exports.getStatsQueryOptions=cE;exports.getSubscribers=cw;exports.getSubscriptions=aw;exports.getSupportSettingsQueryOptions=CK;exports.getSupportSettingsRequest=$d;exports.getTradeHistoryQueryOptions=HR;exports.getTransactionsInfiniteQueryOptions=Rh;exports.getTrendingTagsQueryOptions=o_;exports.getTrendingTagsWithStatsQueryOptions=l_;exports.getUserPostVoteQueryOptions=C_;exports.getUserProposalVotesQueryOptions=sC;exports.getVestingDelegationExpirationsQueryOptions=EC;exports.getVestingDelegationsQueryOptions=_C;exports.getVisibleFirstLevelThreadItems=Pi;exports.getWavesByAccountQueryOptions=nv;exports.getWavesByHostQueryOptions=Nb;exports.getWavesByTagQueryOptions=Vb;exports.getWavesFeedQueryOptions=xb;exports.getWavesFollowingQueryOptions=Gb;exports.getWavesLatestFeedQueryOptions=Eb;exports.getWavesTrendingAuthorsQueryOptions=av;exports.getWavesTrendingTagsQueryOptions=Xb;exports.getWithdrawRoutesQueryOptions=UC;exports.getWitnessVoterCountQueryOptions=xD;exports.getWitnessVotersPageQueryOptions=OD;exports.getWitnessesInfiniteQueryOptions=PD;exports.hasThreeSpeakEmbed=yp;exports.hiveTxConfig=E;exports.hiveTxUtils=re;exports.hsTokenRenew=lB;exports.invalidateAfterBroadcast=S;exports.isCommunity=Xn;exports.isEmptyDate=Zn;exports.isInfoError=Rs;exports.isNetworkError=Fs;exports.isQueryableAccountName=Le;exports.isResourceCreditsError=Ts;exports.isThreeSpeakBeneficiary=Dx;exports.isVoteAlreadyReflected=op;exports.isWif=jn;exports.isWrappedResponse=js;exports.lookupAccountsQueryOptions=Ty;exports.makeQueryClient=Ym;exports.mapMetaChoicesToPollChoices=_B;exports.mapThreadItemsToWaveEntries=Oi;exports.markNotifications=Ki;exports.measureQuestContentLength=Up;exports.moveSchedule=Li;exports.normalizePost=yi;exports.normalizeSearchAuthor=Ed;exports.normalizeSearchCategory=Sd;exports.normalizeSearchTags=kd;exports.normalizeToWrappedResponse=oe;exports.normalizeWaveEntryFromApi=me;exports.onboardEmail=q0;exports.parseAccounts=Ft;exports.parseAsset=C;exports.parseChainError=Ue;exports.parsePostingMetadataRoot=sa;exports.parseProfileMetadata=Ie;exports.pickRicherMetadataSnapshot=ni;exports.powerRechargeTime=IP;exports.proMembersSet=Hv;exports.rcPower=KP;exports.removeOptimisticDiscussionEntry=$i;exports.resolveAccountHistoryLimit=Nl;exports.resolveHiveOperationFilters=ft;exports.resolvePost=li;exports.restoreDiscussionSnapshots=Wi;exports.restoreEntryInCache=LO;exports.roleMap=ok;exports.saveNotificationSetting=C0;exports.search=YD;exports.searchPath=XD;exports.searchQueryOptions=$D;exports.sha256=Pm;exports.shouldTriggerAuthFallback=he;exports.signUp=x0;exports.similar=xo;exports.sortDiscussions=Za;exports.subscribeEmail=E0;exports.toEntryArray=wc;exports.updateDraft=Hi;exports.updateEntryInCache=jO;exports.updateSupportSettingsRequest=zd;exports.uploadImage=Ni;exports.uploadImageWithSignature=R0;exports.useAccountFavoriteAdd=DA;exports.useAccountFavoriteDelete=QA;exports.useAccountRelationsUpdate=Xv;exports.useAccountRevokeKey=hP;exports.useAccountRevokePosting=rP;exports.useAccountUpdate=Wv;exports.useAccountUpdateKeyAuths=Ri;exports.useAccountUpdatePassword=JA;exports.useAccountUpdateRecovery=uP;exports.useAddDraft=N0;exports.useAddFragment=u0;exports.useAddImage=gO;exports.useAddSchedule=eO;exports.useAiAssist=Ng;exports.useAiTranscribe=Ug;exports.useBookmarkAdd=SA;exports.useBookmarkDelete=RA;exports.useBoostPlus=iB;exports.useBroadcastMutation=v;exports.useBuyStreakFreeze=YE;exports.useClaimAccount=vP;exports.useClaimEngineRewards=zI;exports.useClaimInterest=OI;exports.useClaimPoints=FD;exports.useClaimRewards=CI;exports.useComment=QO;exports.useConvert=wI;exports.useCreateAccount=CP;exports.useCrossPost=ex;exports.useDelegateEngineToken=qI;exports.useDelegateRc=uD;exports.useDelegateVestingShares=Mq;exports.useDeleteComment=JO;exports.useDeleteDraft=z0;exports.useDeleteImage=bO;exports.useDeleteSchedule=oO;exports.useEditFragment=y0;exports.useEngineMarketOrder=ZI;exports.useFollow=wA;exports.useGameClaim=NE;exports.useGenerateImage=Ig;exports.useGrantPostingPermission=xP;exports.useLimitOrderCancel=nF;exports.useLimitOrderCreate=ZR;exports.useMarkNotificationsRead=Nk;exports.useMoveSchedule=pO;exports.useMutePost=uS;exports.usePinPost=xS;exports.usePollVote=EB;exports.usePromote=cx;exports.useProposalCreate=mC;exports.useProposalVote=pC;exports.useRcDelegation=cB;exports.useReblog=KO;exports.useRecordActivity=Wr;exports.useRegisterCommunityRewards=vS;exports.useRemoveFragment=A0;exports.useSetCommunityRole=fS;exports.useSetLastRead=Uk;exports.useSetWithdrawVestingRoute=jq;exports.useSignOperationByHivesigner=YP;exports.useSignOperationByKey=jP;exports.useSignOperationByKeychain=WP;exports.useStakeEngineToken=HI;exports.useSubscribeCommunity=tS;exports.useTransfer=Cq;exports.useTransferEngineToken=Gq;exports.useTransferFromSavings=iI;exports.useTransferPoint=Iq;exports.useTransferToSavings=Zq;exports.useTransferToVesting=uI;exports.useUndelegateEngineToken=BI;exports.useUnfollow=PA;exports.useUnstakeEngineToken=LI;exports.useUnsubscribeCommunity=oS;exports.useUpdateCommunity=hS;exports.useUpdateDraft=V0;exports.useUpdateReply=ix;exports.useUpdateSupportSettings=IK;exports.useUploadImage=OO;exports.useVote=RO;exports.useWalletOperation=oD;exports.useWithdrawVesting=mI;exports.useWitnessProxy=hD;exports.useWitnessVote=fD;exports.usrActivity=S0;exports.utf8ByteLength=fr;exports.validatePostCreating=pp;exports.varintByteLength=je;exports.verifyPostOnAlternateNode=ui;exports.vestsToHp=Ve;exports.votingPower=qP;exports.votingRshares=Iu;exports.votingValue=BP;exports.withTimeoutSignal=we;//# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/packages/sdk/dist/node/index.cjs.map b/packages/sdk/dist/node/index.cjs.map index 3efa053fee..fd91b491c6 100644 --- a/packages/sdk/dist/node/index.cjs.map +++ b/packages/sdk/dist/node/index.cjs.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","ByteBuffer","_ByteBuffer","capacity","littleEndian","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","expiration","props","refBlockPrefix","expirationIso","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","count","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"],"mappings":"wkBASA,IAAMA,EAAAA,CAAe,IAAI,YAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,EAAAA,EAAgD,CACvD,OAAKF,EAAAA,GACC,OAAO,YAAgB,GAAA,CACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,OAAOG,CAAAA,CAAuB,CAE5B,IAAMC,CAAAA,CAAiB,GACvB,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,IAAK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,IAAI,MAAM,CAAA,kCAAA,EAAgCA,CAAAA,CAAS,MAAM,CAAA,CAAE,CAAA,CAGnE,IAAMpO,CAAAA,CAAO,MAAMoO,CAAAA,CAAS,MAAK,CAEjC,GAAI,CAAC,KAAA,CAAM,OAAA,CAAQpO,CAAI,GAAK,CAACA,CAAAA,CAAK,CAAC,CAAA,CACjC,MAAM,IAAI,MAAM,wCAAmC,CAAA,CAGrD,OAAOsoD,EAAAA,CAActoD,CAAAA,CAAK,CAAC,CAAC,CAC9B,CACF,CAAC,CACH,CChGO,SAAS6oD,GACdj4C,CAAAA,CACAyH,CAAAA,CACAI,CAAAA,CACA,CACA,OAAOkB,CAAAA,CACL4F,EAAU,KAAA,CAAM,IAAA,EAAK,CACrB3O,CAAAA,EAAY,EAAA,CACZ,CAAC,CAAE,SAAA,CAAAk4C,CAAAA,CAAW,QAAAJ,CAAQ,CAAA,GAAM,CAC1B,GAAI,CAAC93C,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,4DAA4D,CAAA,CAE9E,OAAO,CACL,CACE,aAAA,CACA,CACE,GAAI,OAAA,CACJ,cAAA,CAAgB,EAAC,CACjB,sBAAA,CAAwB,CAACA,CAAQ,CAAA,CACjC,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACnB,IAAA,CAAMk4C,EACN,MAAA,CAAQ,MAAA,CACR,OAAA,CAAAJ,CACF,CAAC,CACH,CACF,CACF,CACF,CAAA,CACA,MAAA,CACArwC,CAAAA,CACA,SAAA,CACA,CAAE,aAAA,CAAeI,CAAAA,EAAiB,OAAQ,CAC5C,CACF","file":"index.cjs","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/core/utf8.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts","../../src/modules/resource-credits/types/resource-params.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/resource-credits/utils/estimate-comment-rc-cost.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","ByteBuffer","_ByteBuffer","capacity","littleEndian","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","expiration","props","refBlockPrefix","expirationIso","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","utf8ByteLength","varintByteLength","count","remaining","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","getRcResourceParamsQueryOptions","RC_RESOURCE_NAMES","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","TRANSACTION_HEADER_BYTES","SIGNATURE_BYTES","ASSET_BYTES","big","computeResourceCost","curve","pool","resourceCount","regenShare","coeffA","coeffB","shift","denom","countCommentResourceUsage","transactionBytes","permlinkLength","signatures","hasCommentOptions","sizeInfo","state","exec","stringFieldBytes","commentOperationBytes","commentOptionsBytes","route","estimateCommentTransactionBytes","estimateCommentRcCost","rcParams","usage","regen","cost","breakdown","share","scaled","resourceCost","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"],"mappings":"wkBASA,IAAMA,EAAAA,CAAe,IAAI,YAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,EAAAA,EAAgD,CACvD,OAAKF,EAAAA,GACC,OAAO,YAAgB,GAAA,CACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,OAAOG,CAAAA,CAAuB,CAE5B,IAAMC,CAAAA,CAAiB,GACvB,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,IAAK,CACjC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CAACA,CAAAA,CAAK,CAAC,CAAA,CACjC,MAAM,IAAI,MAAM,wCAAmC,CAAA,CAGrD,OAAO8qD,EAAAA,CAAc9qD,CAAAA,CAAK,CAAC,CAAC,CAC9B,CACF,CAAC,CACH,CChGO,SAASqrD,GACdz6C,CAAAA,CACAyH,CAAAA,CACAI,CAAAA,CACA,CACA,OAAOkB,CAAAA,CACL4F,EAAU,KAAA,CAAM,IAAA,EAAK,CACrB3O,CAAAA,EAAY,EAAA,CACZ,CAAC,CAAE,SAAA,CAAA06C,CAAAA,CAAW,QAAAJ,CAAQ,CAAA,GAAM,CAC1B,GAAI,CAACt6C,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,4DAA4D,CAAA,CAE9E,OAAO,CACL,CACE,aAAA,CACA,CACE,GAAI,OAAA,CACJ,cAAA,CAAgB,EAAC,CACjB,sBAAA,CAAwB,CAACA,CAAQ,CAAA,CACjC,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACnB,IAAA,CAAM06C,EACN,MAAA,CAAQ,MAAA,CACR,OAAA,CAAAJ,CACF,CAAC,CACH,CACF,CACF,CACF,CAAA,CACA,MAAA,CACA7yC,CAAAA,CACA,SAAA,CACA,CAAE,aAAA,CAAeI,CAAAA,EAAiB,OAAQ,CAC5C,CACF","file":"index.cjs","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n resourceParams: () => [\"resource-credits\", \"resource-params\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","/**\n * UTF-8 byte length of a string.\n *\n * `TextEncoder` is missing on some runtimes the SDK ships to (React Native /\n * Hermes), and `String.length` is NOT a substitute: it counts UTF-16 code\n * units, so anything non-ASCII is undercounted. Where that number feeds an RC\n * estimate, undercounting means telling someone a post is affordable when the\n * chain will reject it.\n */\nexport function utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).length;\n }\n\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const c = value.charCodeAt(i);\n if (c < 0x80) {\n bytes += 1;\n } else if (c < 0x800) {\n bytes += 2;\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < value.length) {\n // surrogate pair encodes as four bytes\n i++;\n bytes += 4;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n\n/** Byte length of Hive's unsigned LEB128 varint for `value`. */\nexport function varintByteLength(value: number): number {\n let count = 0;\n let remaining = value;\n do {\n count++;\n remaining >>>= 7;\n } while (remaining > 0);\n return count;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { RcResourceParams } from \"../types/resource-params\";\n\n/**\n * Curve coefficients and sizing constants used to price resource usage.\n *\n * These only change at a hardfork, so the entry is kept for the session:\n * `gcTime: Infinity` is the one value that schedules no gc timer at all, so it\n * does not hold a request's query cache open on the server the way a long\n * finite window would.\n *\n * `staleTime` stays bounded on purpose. Making it infinite too would mean a\n * long-lived session keeps pricing with pre-hardfork coefficients forever,\n * quietly producing wrong RC estimates with no way to recover short of a\n * reload. A day is long enough that this is effectively never refetched, and\n * short enough that a hardfork corrects itself.\n */\nexport function getRcResourceParamsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.resourceCredits.resourceParams(),\n staleTime: 24 * 60 * 60 * 1000,\n gcTime: Infinity,\n queryFn: async () => (await callRPC(\"rc_api.get_resource_params\", {})) as RcResourceParams\n });\n}\n","/** Shape returned by `rc_api.get_resource_params`. Numbers arrive as strings. */\nexport interface RcPriceCurveParams {\n coeff_a: string | number;\n coeff_b: string | number;\n shift: string | number;\n}\n\nexport interface RcResourceDynamicsParams {\n resource_unit: string | number;\n budget_per_time_unit: string | number;\n pool_eq: string | number;\n max_pool_size: string | number;\n}\n\nexport interface RcResourceParamEntry {\n resource_dynamics_params: RcResourceDynamicsParams;\n price_curve_params: RcPriceCurveParams;\n}\n\n/**\n * Per-operation and per-transaction sizing constants. Only the members this\n * module needs are declared; the node returns many more.\n */\nexport interface RcSizeInfo {\n resource_state_bytes: {\n comment_base_size: number;\n comment_permlink_char_size: number;\n comment_beneficiaries_member_size: number;\n transaction_base_size: number;\n [key: string]: number;\n };\n resource_execution_time: {\n comment_time: number;\n comment_options_time: number;\n transaction_time: number;\n verify_authority_time: number;\n [key: string]: number;\n };\n [key: string]: Record;\n}\n\nexport interface RcResourceParams {\n resource_params: Record;\n size_info: RcSizeInfo;\n}\n\n/**\n * Resource order is consensus-defined (`HIVE_RC_NUM_RESOURCE_TYPES`) and the\n * `pool`, `share` and `budget` arrays in rc_stats are indexed by it.\n */\nexport const RC_RESOURCE_NAMES = [\n \"resource_history_bytes\",\n \"resource_new_accounts\",\n \"resource_market_bytes\",\n \"resource_state_bytes\",\n \"resource_execution_time\"\n] as const;\n\nexport type RcResourceName = (typeof RC_RESOURCE_NAMES)[number];\n\nexport interface RcCostBreakdown {\n resource: RcResourceName;\n usage: number;\n cost: number;\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcPriceCurveParams,\n type RcResourceName,\n type RcResourceParams,\n type RcSizeInfo\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * What the chain actually charges for publishing a comment, rather than the\n * network-average cost of an average comment.\n *\n * The average is a poor guide for posts: it is dominated by short replies,\n * while a long post is charged mostly on `history_bytes`, which is the\n * serialized transaction size. A real case: an account holding 21.3B RC was\n * told it could afford 17 posts, then a 46,620-byte post was rejected needing\n * 23.3B RC, more than that account's entire maximum.\n *\n * This is a direct port of `resource_credits::compute_cost` and the\n * `comment_operation` arm of `count_resources` from hive, so it tracks what\n * the node does instead of approximating it. Verified against a real\n * rejection: usage reproduces exactly and total cost lands within 0.3%, the\n * residual coming from `share` being published rounded to four digits.\n */\n\n/**\n * Fixed transaction header: ref_block_num(2) + ref_block_prefix(4) +\n * expiration(4) + the extensions varint(1).\n */\nconst TRANSACTION_HEADER_BYTES = 11;\n/** Compact signature, 65 bytes each. */\nconst SIGNATURE_BYTES = 65;\n/** asset = amount int64(8) + precision(1) + symbol(7). */\nconst ASSET_BYTES = 16;\n\nconst big = (v: string | number): bigint => BigInt(typeof v === \"string\" ? v : Math.trunc(v));\n\n/**\n * Port of `resource_credits::compute_cost` (libraries/chain/rc/rc_utility.cpp).\n *\n * BigInt is required, not stylistic: `coeff_a` is ~1.05e19, well past\n * Number.MAX_SAFE_INTEGER, so float arithmetic loses the low bits and the\n * result drifts.\n */\nexport function computeResourceCost(\n curve: RcPriceCurveParams,\n pool: number,\n resourceCount: number,\n regenShare: number\n): number {\n if (resourceCount <= 0 || regenShare <= 0) {\n return 0;\n }\n\n const coeffA = big(curve.coeff_a);\n const coeffB = big(curve.coeff_b);\n const shift = big(curve.shift);\n\n // The node shifts before multiplying by the resource count, because\n // regen * coeff_a already risks overflowing 128 bits. Order matters.\n let num = (big(regenShare) * coeffA) >> shift;\n num += 1n;\n num *= big(resourceCount);\n\n const denom = coeffB + (pool > 0 ? big(pool) : 0n);\n if (denom === 0n) {\n return 0;\n }\n\n return Number(num / denom + 1n);\n}\n\nexport interface CommentResourceUsageInput {\n /** Byte length of the serialized transaction. */\n transactionBytes: number;\n permlinkLength: number;\n /** Signatures on the transaction; a normal post carries one. */\n signatures?: number;\n /**\n * Beneficiary count on the companion comment_options, when publish appends\n * one. The chain counts resources for every operation in the transaction,\n * not just the comment.\n */\n beneficiaries?: number;\n hasCommentOptions?: boolean;\n}\n\n/**\n * Port of the `comment_operation` and `comment_options_operation` arms of\n * `count_resources` (libraries/chain/rc/resource_count.cpp). Reproduces the\n * chain's numbers exactly, see the spec.\n */\nexport function countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength,\n signatures = 1,\n beneficiaries = 0,\n hasCommentOptions = false\n }: CommentResourceUsageInput,\n sizeInfo: RcSizeInfo\n): Record {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n resource_history_bytes: transactionBytes,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes:\n state.comment_base_size +\n state.comment_permlink_char_size * permlinkLength +\n state.transaction_base_size +\n // comment_payout_beneficiaries is visited from comment_options\n state.comment_beneficiaries_member_size * beneficiaries,\n resource_execution_time:\n exec.comment_time +\n exec.transaction_time +\n exec.verify_authority_time * signatures +\n (hasCommentOptions ? exec.comment_options_time : 0)\n };\n}\n\nexport interface CommentLike {\n author: string;\n permlink: string;\n parent_author: string;\n parent_permlink: string;\n title: string;\n body: string;\n json_metadata: string;\n}\n\n\n/** A beneficiary route as it appears in comment_options extensions. */\nexport interface BeneficiaryRoute {\n account: string;\n weight: number;\n}\n\n/**\n * The comment_options operation publish appends when the author sets\n * beneficiaries or a non-default reward split.\n */\nexport interface CommentOptionsLike {\n beneficiaries?: BeneficiaryRoute[];\n}\n\n/** Serialized bytes of one string field: its varint length plus its bytes. */\nconst stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst commentOperationBytes = (op: CommentLike): number =>\n 1 + // operation variant id\n stringFieldBytes(op.parent_author) +\n stringFieldBytes(op.parent_permlink) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n stringFieldBytes(op.title) +\n stringFieldBytes(op.body) +\n stringFieldBytes(op.json_metadata);\n\nconst commentOptionsBytes = (op: CommentLike, options: CommentOptionsLike): number => {\n const beneficiaries = options.beneficiaries ?? [];\n let bytes =\n 1 + // operation variant id\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n ASSET_BYTES + // max_accepted_payout\n 2 + // percent_hbd\n 2; // allow_votes + allow_curation_rewards\n\n bytes += varintByteLength(beneficiaries.length > 0 ? 1 : 0);\n if (beneficiaries.length > 0) {\n bytes += 1 + varintByteLength(beneficiaries.length); // extension variant id + route count\n beneficiaries.forEach((route) => {\n bytes += stringFieldBytes(route.account) + 2; // weight is uint16\n });\n }\n return bytes;\n};\n\nexport interface CommentTransactionInput {\n op: CommentLike;\n /** Present when publish appends comment_options for beneficiaries or rewards. */\n options?: CommentOptionsLike;\n signatures?: number;\n}\n\n/**\n * Serialized size of the transaction that will carry this comment.\n *\n * This models Hive's binary encoding rather than approximating it: a fixed\n * header, one varint-prefixed field per string, and 65 bytes per signature.\n * Verified byte-exact against eight real transactions read back with\n * `get_transaction_hex`, including one carrying comment_options.\n */\nexport function estimateCommentTransactionBytes({\n op,\n options,\n signatures = 1\n}: CommentTransactionInput): number {\n const operations = [commentOperationBytes(op)];\n if (options) {\n operations.push(commentOptionsBytes(op, options));\n }\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(operations.length) +\n operations.reduce((sum, bytes) => sum + bytes, 0) +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\nexport interface EstimateCommentRcCostInput {\n op: CommentLike;\n /** Companion comment_options, when the author set beneficiaries or rewards. */\n options?: CommentOptionsLike;\n rcParams: RcResourceParams | undefined;\n rcStats: Pick | undefined;\n signatures?: number;\n}\n\nexport interface CommentRcCostEstimate {\n /** False until both queries have resolved; callers must not warn on this. */\n ready: boolean;\n cost: number;\n transactionBytes: number;\n breakdown: RcCostBreakdown[];\n}\n\nconst EMPTY: CommentRcCostEstimate = {\n ready: false,\n cost: 0,\n transactionBytes: 0,\n breakdown: []\n};\n\n/** Total RC the chain will charge to broadcast this comment. */\nexport function estimateCommentRcCost({\n op,\n options,\n rcParams,\n rcStats,\n signatures = 1\n}: EstimateCommentRcCostInput): CommentRcCostEstimate {\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats?.pool || !rcStats.share) {\n return EMPTY;\n }\n\n const transactionBytes = estimateCommentTransactionBytes({ op, options, signatures });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: utf8ByteLength(op.permlink),\n signatures,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n\n const regen = Number(rcStats.regen);\n let cost = 0;\n const breakdown: RcCostBreakdown[] = [];\n\n RC_RESOURCE_NAMES.forEach((name, index) => {\n const entry = rcParams.resource_params[name];\n const pool = Number(rcStats.pool[index] ?? 0);\n const share = Number(rcStats.share[index] ?? 0);\n if (!entry || share <= 0) {\n return;\n }\n\n // `usage` is scaled by the resource unit before pricing. It is 1 for the\n // resources a comment touches, but market bytes and new accounts are not.\n const scaled = usage[name] * Number(entry.resource_dynamics_params.resource_unit ?? 1);\n // rc_stats publishes `share` as weight/divisor scaled to 10,000. Kept in\n // BigInt: regen is ~2.4e12 and the product is past the safe-integer range\n // for larger shares.\n const regenShare = Number((BigInt(regen) * BigInt(share)) / 10000n);\n const resourceCost = computeResourceCost(entry.price_curve_params, pool, scaled, regenShare);\n\n cost += resourceCost;\n breakdown.push({ resource: name, usage: scaled, cost: resourceCost });\n });\n\n return { ready: true, cost, transactionBytes, breakdown };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file diff --git a/packages/sdk/dist/node/index.mjs b/packages/sdk/dist/node/index.mjs index 453022f8e0..e028691ba5 100644 --- a/packages/sdk/dist/node/index.mjs +++ b/packages/sdk/dist/node/index.mjs @@ -1,10 +1,10 @@ -import {useQuery,useInfiniteQuery,useMutation,QueryClient,queryOptions,infiniteQueryOptions,useQueryClient,isServer}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import rn from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import jn from'hivesigner';var Ao=Object.defineProperty;var mt=(e,t)=>{for(var r in t)Ao(e,r,{get:t[r],enumerable:true});};var gt=new ArrayBuffer(0),yt=null,ht=null;function Po(){return yt||(typeof TextEncoder<"u"?yt=new TextEncoder:yt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),yt}function Jr(){return ht||(typeof TextDecoder<"u"?ht=new TextDecoder:ht={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),ht}var I=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?gt:new ArrayBuffer(t),this.view=t===0?new DataView(gt):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(gt));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof e?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,i=new e(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?gt:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=Po().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=Jr().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=Jr().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};var x={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},$t=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Wt=e=>{let t=$t(e);t.length&&(x.nodes=t);},Gt=e=>{let t=$t(e);t.length&&(x.restNodes=t);},zt=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=$t(n);i.length?t[r]=i:delete t[r];}x.restNodesByApi=t;},Jt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},Yt=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var Ae=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new J(n.recoverPublicKey(t).toBytes())}};var J=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??x.address_prefix;}static fromString(t){let r=x.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=rn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=ripemd160(o).subarray(0,4);if(!xo(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Ae.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Oo(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Oo=(e,t)=>{let r=ripemd160(e);return t+rn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},xo=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},_=(e,t)=>{e.writeVString(t);},ko=(e,t)=>{e.writeInt16(t);},on=(e,t)=>{e.writeInt64(t);},nn=(e,t)=>{e.writeUint8(t);},ue=(e,t)=>{e.writeUint16(t);},Y=(e,t)=>{e.writeUint32(t);},sn=(e,t)=>{e.writeUint64(t);},ge=(e,t)=>{e.writeByte(t?1:0);},an=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},q=(e,t)=>{let r=wt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},Pe=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},fe=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(J.from(t).key);},un=(e=null)=>(t,r)=>{r=_t.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},cn=un(),Xt=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ce=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},ke=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=ce([["weight_threshold",Y],["account_auths",Xt(_,ue)],["key_auths",Xt(fe,ue)]]),Co=ce([["account",_],["weight",ue]]),Zt=ce([["base",q],["quote",q]]),To=ce([["account_creation_fee",q],["maximum_block_size",Y],["hbd_interest_rate",ue]]),R=(e,t)=>{let r=ce(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},k={};k.account_create=R(T.account_create,[["fee",q],["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_]]);k.account_create_with_delegation=R(T.account_create_with_delegation,[["fee",q],["delegation",q],["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_],["extensions",V(ie)]]);k.account_update=R(T.account_update,[["account",_],["owner",ke(W)],["active",ke(W)],["posting",ke(W)],["memo_key",fe],["json_metadata",_]]);k.account_witness_proxy=R(T.account_witness_proxy,[["account",_],["proxy",_]]);k.account_witness_vote=R(T.account_witness_vote,[["account",_],["witness",_],["approve",ge]]);k.cancel_transfer_from_savings=R(T.cancel_transfer_from_savings,[["from",_],["request_id",Y]]);k.change_recovery_account=R(T.change_recovery_account,[["account_to_recover",_],["new_recovery_account",_],["extensions",V(ie)]]);k.claim_account=R(T.claim_account,[["creator",_],["fee",q],["extensions",V(ie)]]);k.claim_reward_balance=R(T.claim_reward_balance,[["account",_],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);k.comment=R(T.comment,[["parent_author",_],["parent_permlink",_],["author",_],["permlink",_],["title",_],["body",_],["json_metadata",_]]);k.comment_options=R(T.comment_options,[["author",_],["permlink",_],["max_accepted_payout",q],["percent_hbd",ue],["allow_votes",ge],["allow_curation_rewards",ge],["extensions",V(an([ce([["beneficiaries",V(Co)]])]))]]);k.convert=R(T.convert,[["owner",_],["requestid",Y],["amount",q]]);k.create_claimed_account=R(T.create_claimed_account,[["creator",_],["new_account_name",_],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",_],["extensions",V(ie)]]);k.custom=R(T.custom,[["required_auths",V(_)],["id",ue],["data",cn]]);k.custom_json=R(T.custom_json,[["required_auths",V(_)],["required_posting_auths",V(_)],["id",_],["json",_]]);k.decline_voting_rights=R(T.decline_voting_rights,[["account",_],["decline",ge]]);k.delegate_vesting_shares=R(T.delegate_vesting_shares,[["delegator",_],["delegatee",_],["vesting_shares",q]]);k.delete_comment=R(T.delete_comment,[["author",_],["permlink",_]]);k.escrow_approve=R(T.escrow_approve,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Y],["approve",ge]]);k.escrow_dispute=R(T.escrow_dispute,[["from",_],["to",_],["agent",_],["who",_],["escrow_id",Y]]);k.escrow_release=R(T.escrow_release,[["from",_],["to",_],["agent",_],["who",_],["receiver",_],["escrow_id",Y],["hbd_amount",q],["hive_amount",q]]);k.escrow_transfer=R(T.escrow_transfer,[["from",_],["to",_],["hbd_amount",q],["hive_amount",q],["escrow_id",Y],["agent",_],["fee",q],["json_meta",_],["ratification_deadline",Pe],["escrow_expiration",Pe]]);k.feed_publish=R(T.feed_publish,[["publisher",_],["exchange_rate",Zt]]);k.limit_order_cancel=R(T.limit_order_cancel,[["owner",_],["orderid",Y]]);k.limit_order_create=R(T.limit_order_create,[["owner",_],["orderid",Y],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",ge],["expiration",Pe]]);k.limit_order_create2=R(T.limit_order_create2,[["owner",_],["orderid",Y],["amount_to_sell",q],["exchange_rate",Zt],["fill_or_kill",ge],["expiration",Pe]]);k.recover_account=R(T.recover_account,[["account_to_recover",_],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);k.request_account_recovery=R(T.request_account_recovery,[["recovery_account",_],["account_to_recover",_],["new_owner_authority",W],["extensions",V(ie)]]);k.reset_account=R(T.reset_account,[["reset_account",_],["account_to_reset",_],["new_owner_authority",W]]);k.set_reset_account=R(T.set_reset_account,[["account",_],["current_reset_account",_],["reset_account",_]]);k.set_withdraw_vesting_route=R(T.set_withdraw_vesting_route,[["from_account",_],["to_account",_],["percent",ue],["auto_vest",ge]]);k.transfer=R(T.transfer,[["from",_],["to",_],["amount",q],["memo",_]]);k.transfer_from_savings=R(T.transfer_from_savings,[["from",_],["request_id",Y],["to",_],["amount",q],["memo",_]]);k.transfer_to_savings=R(T.transfer_to_savings,[["from",_],["to",_],["amount",q],["memo",_]]);k.transfer_to_vesting=R(T.transfer_to_vesting,[["from",_],["to",_],["amount",q]]);k.vote=R(T.vote,[["voter",_],["author",_],["permlink",_],["weight",ko]]);k.withdraw_vesting=R(T.withdraw_vesting,[["account",_],["vesting_shares",q]]);k.witness_update=R(T.witness_update,[["owner",_],["url",_],["block_signing_key",fe],["props",To],["fee",q]]);k.witness_set_properties=R(T.witness_set_properties,[["owner",_],["props",Xt(_,cn)],["extensions",V(ie)]]);k.account_update2=R(T.account_update2,[["account",_],["owner",ke(W)],["active",ke(W)],["posting",ke(W)],["memo_key",ke(fe)],["json_metadata",_],["posting_json_metadata",_],["extensions",V(ie)]]);k.create_proposal=R(T.create_proposal,[["creator",_],["receiver",_],["start_date",Pe],["end_date",Pe],["daily_pay",q],["subject",_],["permlink",_],["extensions",V(ie)]]);k.update_proposal_votes=R(T.update_proposal_votes,[["voter",_],["proposal_ids",V(on)],["approve",ge],["extensions",V(ie)]]);k.remove_proposal=R(T.remove_proposal,[["proposal_owner",_],["proposal_ids",V(on)],["extensions",V(ie)]]);var Ro=ce([["end_date",Pe]]);k.update_proposal=R(T.update_proposal,[["proposal_id",sn],["creator",_],["daily_pay",q],["subject",_],["permlink",_],["extensions",V(an([ie,Ro]))]]);k.collateralized_convert=R(T.collateralized_convert,[["owner",_],["requestid",Y],["amount",q]]);k.recurrent_transfer=R(T.recurrent_transfer,[["from",_],["to",_],["amount",q],["memo",_],["recurrence",ue],["executions",ue],["extensions",V(ce([["type",nn],["value",ce([["pair_id",nn]])]]))]]);var Fo=(e,t)=>{let r=k[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},qo=ce([["ref_block_num",ue],["ref_block_prefix",Y],["expiration",Pe],["operations",V(Fo)],["extensions",V(_)]]),Io=ce([["from",fe],["to",fe],["nonce",sn],["check",Y],["encrypted",un()]]),pe={Asset:q,Memo:Io,Price:Zt,PublicKey:fe,String:_,Transaction:qo,UInt16:ue,UInt32:Y};var Xe=e=>new Promise(t=>setTimeout(t,e));var Do=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function fn(){return Do?{"User-Agent":x.userAgent}:{}}var X=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},Ce=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function mn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Ko=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Bo=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Mo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function No(e){if(!e)return false;if(e instanceof Ce)return true;if(e instanceof X)return false;let t=Mo(e);return !!(Ko.some(r=>t.includes(r))||Bo.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function er(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function gn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Qo=1e4,Ho=6e4,Uo=12e4,pn=2,ln=6e4,dn=12e4,Vo=30,Ze=.3,tr=3,et=5*6e4,yn=6e4,hn=1e3,wn=2e3,vt=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=tr&&i-o.updatedAt<=et?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>et&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:Ze*r+(1-Ze)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>et?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=Ze*r+(1-Ze)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=pn&&(o.cooldownUntil=i+ln),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,pn),o.lastFailureTime=i,o.cooldownUntil=i+ln,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>Uo&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(Qo*2**n.rateLimitStreak,Ho);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=dn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=dn&&o-n.headBlock>Vo)}getOrderedNodes(t,r){let n=[],i=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):i.push(c);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,o)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=tr&&r-t.latencyUpdatedAt<=et}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:hn}pickReprobeCandidate(t,r){let n=r-yn,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),c=Math.max(a.latencyUpdatedAt,a.lastProbeAt);c<=n&&c=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(x.resilience.hedgeBucketCapacity,this.tokens+x.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>x.resilience.hedgeBucketCapacity&&(this.tokens=x.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=x.resilience.hedgeBucketCapacity){this.tokens=t;}},nr=new rr;function At(e,t,r,n,i){let o=x.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function ir(e,t,r,n){r instanceof Ce?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof X?e.recordFailure(t,n):e.recordFailure(t);}function _n(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function jo(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function bn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(jo()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function or(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var tt=async(e,t,r,n=x.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=bn(n),{signal:l,cleanup:f}=or(c,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...fn()},signal:l});if(y.status===429)throw new Ce(e,"HTTP 429 Rate Limited",{rateLimitMs:mn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new Ce(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let E=h.error;throw "message"in E&&"code"in E?new X(E):h.error}throw h}catch(y){if(y instanceof X||y instanceof Ce||o?.aborted)throw y;if(i)return tt(e,t,r,n,false,o);throw y}finally{m();}};function bt(){return Xe(50+Math.random()*50)}function Lo(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,E=0,O=false,A=false,P,L,U=0,B=[],Q=z=>{if(!h){h=true,L!==void 0&&(clearTimeout(L),L=void 0);for(let F of B)F.signal.aborted||F.abort();z();}},$=(z,F)=>{E++;let de=new AbortController;B.push(de);let Ye=or(de.signal,p),vo=At(j,z,t,s,a),Lt=Date.now();F||(U=Lt),tt(z,t,r,vo,false,Ye.signal).then(ne=>{if(Ye.cleanup(),E--,F||(A=true),!h){if(f&&!f(ne)){if(j.recordDefectiveResponse(z,n),P=new Error(`[hive-tx] response validation failed for ${t} from ${z}`),!F&&!O){Q(()=>y(P));return}E===0&&Q(()=>y(P));return}j.recordSuccess(z,n,Date.now()-Lt,t),_n(j,z,t,ne),F?A||j.recordCensoredLatency(i,Date.now()-U,t):O||nr.refill(),Q(()=>m(ne));}}).catch(ne=>{if(Ye.cleanup(),E--,F||(A=true),!h){if(p?.aborted){Q(()=>y(ne));return}if(ne instanceof X&&!er(ne.code,ne.message)){Q(()=>y(ne));return}if(ir(j,z,ne,n),j.recordSlowFailure(z,Date.now()-Lt,t),P=ne,!F&&!O){Q(()=>y(ne));return}E===0&&Q(()=>y(P));}});};$(i,false);let Se=j.getUsableLatencyMs(i,t)??0,Je=At(j,i,t,s,a),jt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*Se),.8*Je);L=setTimeout(()=>{if(L=void 0,h||p?.aborted||Date.now()>=c)return;let z=o.filter(de=>j.isNodeHealthy(de,n));if(z.length===0)return;let F=z[Math.floor(Math.random()*z.length)];nr.trySpend()&&(O=true,l(F),$(F,true));},jt);})}var g=async(e,t=[],r,n=x.retry,i,o)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??x.timeout,c=gn(e),p=Date.now()+x.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=j.getOrderedNodes(x.nodes,c),h=y.find(A=>!l.has(A));h||(l.clear(),h=y[0]),l.add(h);let E=[];if(x.resilience.hedge&&j.getUsableLatencyMs(h,e)!==void 0&&(E=y.filter(A=>!l.has(A)&&j.isNodeHealthy(A,c)).slice(0,3)),E.length>0)try{return await Lo({method:e,params:t,api:c,primary:h,hedgePool:E,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:A=>l.add(A),validate:o})}catch(A){if(A instanceof X&&!er(A.code,A.message)||i?.aborted)throw A;f=A,m{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let i=gn(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await tt(p,e,t,r,!1,n);return j.recordSuccess(p,i),l}catch(l){if(l instanceof X||n?.aborted||(ir(j,p,l,i),s=l,!No(l)))throw l}}throw s},$o={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function ee(e,t,r,n,i=x.retry,o){if(!Array.isArray(x.restNodes))throw new Error("config.restNodes is not an array");if(x.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??x.timeout,c=Date.now()+x.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=x.restNodesByApi?.[e]?.length?x.restNodesByApi[e]:x.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=c);h++){let E=Oe.getOrderedNodes(l,e),O=E.find(F=>!f.has(F));O||(f.clear(),O=E[0]),f.add(O);let A=O+$o[e],P=t,L=r||{},U=new Set;Object.entries(L).forEach(([F,de])=>{P.includes(`{${F}}`)&&(P=P.replace(`{${F}}`,encodeURIComponent(String(de))),U.add(F));});let B=new URL(A+P);if(Object.entries(L).forEach(([F,de])=>{U.has(F)||(Array.isArray(de)?de.forEach(Ye=>B.searchParams.append(F,String(Ye))):B.searchParams.set(F,String(de)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:Q,cleanup:$}=bn(At(Oe,O,p,a,s)),{signal:Se,cleanup:Je}=or(Q,o),jt=()=>{$(),Je();},z=Date.now();try{let F=await fetch(B.toString(),{signal:Se,headers:fn()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw Oe.recordRateLimit(O,mn(F.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(F.status===503)throw Oe.recordFailure(O,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!F.ok)throw Oe.recordFailure(O,e),y=!0,new Error(`HTTP ${F.status} from ${O}`);return Oe.recordSuccess(O,e,Date.now()-z,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||o?.aborted)throw F;y||Oe.recordFailure(O,e),Oe.recordSlowFailure(O,Date.now()-z,p),m=F,h{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an Array");if(r>x.nodes.length)throw new Error("quorum > config.nodes.length");let o=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(x.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let c=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Wo(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Wo(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var zo=hexToBytes(x.chain_id),Te=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Qe("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof X&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await Xe(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};}};var En=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(Zo(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=hexToBytes(t);else {let n=[];for(let i=0;i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return Ae.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new J(secp256k1.getPublicKey(this.key),t)}toString(){return Xo(new Uint8Array([...En,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},Sn=e=>sha256(sha256(e)),Xo=e=>{let t=Sn(e);return rn.encode(new Uint8Array([...e,...t.slice(0,4)]))},Zo=e=>{let t=rn.decode(e);if(!On(t.slice(0,1),En))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=Sn(n).slice(0,4);if(!On(r,i))throw new Error("Private key checksum mismatch");return n},On=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nRn(e,t,n,r),Tn=(e,t,r,n,i)=>Rn(e,t,r,n,i).message,Rn=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let c=sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),f=sha256(c).subarray(0,4),m=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=ns(n,l,p);}else n=is(n,l,p);return {nonce:o,message:n,checksum:y}},ns=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},is=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},ar=null,os=()=>{if(ar===null){let r=secp256k1.utils.randomSecretKey();ar=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++ar%65536;return e=e<{let t=ls(e,33);return new J(t)},as=e=>e.readUint64(),us=e=>e.readUint32(),cs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},ps=e=>t=>{let r={},n=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function ls(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var ds=ps([["from",Fn],["to",Fn],["nonce",as],["check",us],["encrypted",cs]]),qn={Memo:ds};var Dn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Bn(),e=Mn(e),t=fs(t);let i=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Cn(e,t,o,n),p=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);pe.Memo(p,{check:c,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+rn.encode(l)},Kn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Bn(),e=Mn(e);let r=qn.Memo(rn.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new J(n.key).toString()?new J(i.key):new J(n.key);r=Tn(e,p,o,a,s);let l=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Ot,Bn=()=>{if(Ot===void 0){let e;Ot=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Dn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Kn(t,n);}finally{Ot=e==="#memo\u7231";}}if(Ot===false)throw new Error("This environment does not support encryption.")},Mn=e=>typeof e=="string"?H.fromString(e):e,fs=e=>typeof e=="string"?J.fromString(e):e,Nn={decode:Kn,encode:Dn};var re={};mt(re,{buildWitnessSetProperties:()=>_s,makeBitMaskFilter:()=>hs,operations:()=>ys,validateUsername:()=>gs});var gs=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(ws,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),ws=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=pe.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=pe.UInt32;break;case "hbd_interest_rate":i=pe.UInt16;break;case "url":i=pe.String;break;case "hbd_exchange_rate":i=pe.Price;break;case "account_creation_fee":i=pe.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,bs(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},bs=(e,t)=>{let r=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function um(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function Qn(e){try{return H.fromString(e),!0}catch{return false}}async function Z(e,t){let r=new Te;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Qe("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Hn(e,t){let r=new Te;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var As=432e3;function Un(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/As,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function Ps(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function ur(e){let t=Ps(e)*1e6;return Un(t,e.voting_manabar)}function xt(e){return Un(Number(e.max_rc),e.rc_manabar)}var Vn=(c=>(c.COMMON="common",c.INFO="info",c.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",c.MISSING_AUTHORITY="missing_authority",c.TOKEN_EXPIRED="token_expired",c.NETWORK="network",c.TIMEOUT="timeout",c.VALIDATION="validation",c))(Vn||{});function He(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Os(e){let t=He(e);return [t.message,t.type]}function ye(e){let{type:t}=He(e);return t==="missing_authority"||t==="token_expired"}function xs(e){let{type:t}=He(e);return t==="insufficient_resource_credits"}function Es(e){let{type:t}=He(e);return t==="info"}function Ss(e){let{type:t}=He(e);return t==="network"||t==="timeout"}async function he(e,t,r,n,i="posting",o,s,a="async"){let c=n?.adapter;switch(e){case "key":{if(!c)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(c.getOwnerKey)p=await c.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":c.getActiveKey&&(p=await c.getActiveKey(t));break;case "memo":if(c.getMemoKey)p=await c.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await c.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Hn(r,l):await Z(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new jn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&ye(l))return await c.broadcastWithHiveSigner(t,r,i);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!c?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await c.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Cs(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!ye(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await he(l,e,t,r,n,void 0,void 0,i)}catch(m){if(ye(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await he(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await he("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(ye(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await he(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await he(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let E;switch(n){case "owner":o.getOwnerKey&&(E=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(E=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(E=await o.getMemoKey(e));break;default:E=await o.getPostingKey(e);break}E?y=E:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let E=await o.getAccessToken(e);E&&(h=E);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await he(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!ye(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async c=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(c);try{if(i?.enableFallback!==!1&&i?.adapter)return await Cs(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=H.fromString(l);return await Z(p,m)}let f=i?.accessToken;if(f)return (await new jn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof X?new Error(l.message):l}}})}async function Ln(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let c=H.fromString(o);return Z([["custom_json",i]],c)}let s=n?.accessToken;if(s)return (await new jn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,c,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,c,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Om=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function we(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var Re=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),Fs=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},_e=1e4,$n=120*1e3,Et,qs;function Is(){return Et?Et():qs??=new QueryClient}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:Fs(),get queryClient(){return Is()},set queryClient(e){Et=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},N;(A=>{function e(P){d.queryClient=P;}A.setQueryClient=e;function t(P){Et=P;}A.setQueryClientResolver=t;function r(P){d.privateApiHost=P;}A.setPrivateApiHost=r;function n(P){d.clientId=P;}A.setClientId=n;function i(P){if(typeof P!="string"||P.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=P;}A.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}A.getValidatedBaseUrl=o;function s(P){d.pollsApiHost=P;}A.setPollsApiHost=s;function a(P){d.imageHost=P;}A.setImageHost=a;function c(P){Wt(P);}A.setHiveNodes=c;function p(P){Gt(P);}A.setRestNodes=p;function l(P){zt(P);}A.setRestNodesByApi=l;function f(P){Jt(P);}A.setUserAgent=f;function m(P){Yt(P);}A.setResilience=m;function y(P){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(P))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(P))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(P))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(P)||/\.\+\.\+/.test(P))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let L=/\.?\{(\d+),(\d+)\}/g,U;for(;(U=L.exec(P))!==null;){let[,B,Q]=U;if(parseInt(Q,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${Q}}`}}return {safe:true}}function h(P){let L=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],U=5;for(let B of L){let Q=Date.now();try{P.test(B);let $=Date.now()-Q;if($>U)return {safe:!1,reason:`runtime test exceeded ${U}ms (took ${$}ms on input length ${B.length})`}}catch($){return {safe:false,reason:`runtime test threw error: ${$}`}}}return {safe:true}}function E(P,L=200){try{if(!P)return Re&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(P.length>L)return Re&&console.warn(`[SDK] DMCA pattern rejected: length ${P.length} exceeds max ${L} - pattern: ${P.substring(0,50)}...`),null;let U=y(P);if(!U.safe)return Re&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${U.reason}) - pattern: ${P.substring(0,50)}...`),null;let B;try{B=new RegExp(P);}catch($){return Re&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${P.substring(0,50)}...`,$),null}let Q=h(B);return Q.safe?B:(Re&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Q.reason}) - pattern: ${P.substring(0,50)}...`),null)}catch(U){return Re&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${P.substring(0,50)}...`,U),null}}function O(P={}){let L=$=>Array.isArray($)?$.filter(Se=>typeof Se=="string"):[],U=P||{},B={accounts:L(U.accounts),tags:L(U.tags),patterns:L(U.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map($=>E($)).filter($=>$!==null),d.dmcaPatternRegexes=[];let Q=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Re&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${Q} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),Q>0&&console.warn(`[SDK] ${Q} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}A.setDmcaLists=O;})(N||={});function Km(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,Ms;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(Ms||={});function Mm(e){return btoa(JSON.stringify(e))}function Nm(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Wn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Wn||{}),St=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(St||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Wn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:St[e.nai]}}var cr;function w(){if(!cr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");cr=globalThis.fetch.bind(globalThis);}return cr}function Gn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Ns(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return Ns(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ue(e,t){return e/1e6*t}function zn(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var Jn=60*1e3;function be(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:Jn,staleTime:Jn,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=C(t.total_vesting_shares).amount,a=C(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=C(r.current_median_history.base).amount,l=C(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=C(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",E=Number(i.content_constant??0),O=String(o.current_hardfork_version??"0.0.0"),A=Number(o.last_hardfork??0),P=t.hbd_print_rate,L=t.hbd_interest_rate,U=t.head_block_number,B=a,Q=s,$=C(t.virtual_supply).amount,Se=t.vesting_reward_percent||0,Je=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:E,currentHardforkVersion:O,lastHardfork:A,hbdPrintRate:P,hbdInterestRate:L,headBlock:U,totalVestingFund:B,totalVestingShares:Q,virtualSupply:$,vestingRewardPercent:Se,accountCreationFee:Je,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function tg(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function Fe(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var u={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>Fe("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Fe("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Fe("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Fe("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>Fe("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>Fe("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>Fe("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function sg(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await w()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function pg(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function mg(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await w()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function $s(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function wg(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??$s()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw c.status=i.status,c.data=a,c}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Gs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ag(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await w()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Gs()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Js(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Eg(e,t){return useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??Js()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await w()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),c={};try{c=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:c})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function pr(e){return !e.posting_json_metadata&&!e.json_metadata}function Xs(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function M(e){return queryOptions({queryKey:u.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(pr(i)&&Xs(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!pr(l[0])));if(p[0]&&!pr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=qe(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:c,profile:o}},enabled:!!e,staleTime:6e4})}var Zs=new Set(["__proto__","constructor","prototype"]);function kt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Yn(e,t){let r={...e};for(let n of Object.keys(t)){if(Zs.has(n))continue;let i=t[n],o=r[n];kt(i)&&kt(o)?r[n]=Yn(o,i):r[n]=i;}return r}function ea(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function qe(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function Xn(e){return qe(e?.posting_json_metadata)}function Zn(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(qe(e.posting_json_metadata)).length;return Object.keys(qe(t.posting_json_metadata)).length>r?t:e}function ta(e){if(!e)return {};try{let t=JSON.parse(e);if(kt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ei({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=ta(e),i=kt(n.profile)?n.profile:{},o=lr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function lr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=Yn(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=ea(s.tokens),s.version=2,s}function Ct(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=qe(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function ra(e){return new TextEncoder().encode(e).length}function Ve(e){return e?ra(e)<=16:false}function Ug(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Ve);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ct(r??[])}})}function Wg(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function Xg(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function ny(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var ti=1e3,ua=20;function uy(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthVe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function _y(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var da=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Py(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await w()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,c=typeof a.token=="string"?a.token:void 0;if(!c)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:c,currency:c,address:f,show:y,type:"CHAIN",meta:l},E=[];for(let[O,A]of Object.entries(p))typeof O=="string"&&(da.has(O)||typeof A!="string"||!A||/^[A-Z0-9]{2,10}$/.test(O)&&E.push({symbol:O,currency:O,address:A,show:y,type:"CHAIN",meta:{address:A,show:y}}));return [h,...E]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function ri(e,t){return queryOptions({queryKey:u.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function Fy(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Ky(e,t){return queryOptions({queryKey:u.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function By(e,t,r=10){return infiniteQueryOptions({queryKey:u.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Hy(e,t){return queryOptions({queryKey:u.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Uy(e,t,r=10){return infiniteQueryOptions({queryKey:u.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function $y(e,t,r){return queryOptions({queryKey:u.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await w()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function Jy(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:u.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await w()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function th(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function ah(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Ve(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var D=re.operations,ni={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.fill_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay]},Oa=Array.from(new Set(Object.values(ni).flat()));function xa(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ea(e){return e.replace(/_operation$/,"")}function Sa(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function ka(e){if(!Sa(e))return e;let t=C(e),r=St[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Ca(e){let t={};for(let[r,n]of Object.entries(e))t[r]=ka(n);return t}function gh(e,t=20,r=""){let n=r?ni[r]:Oa;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await ee("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ea(m.op.type);return {...Ca(m.op.value),num:xa(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(i),p=a(c),l=i??c.total_pages;if(i===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function _h(){return queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Ph(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=N.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Sh(e){return queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function qh(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Da=30;function Mh(e,t,r){return queryOptions({queryKey:u.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(c=>t==="following"?c.following:c.follower).filter(c=>c.toLowerCase().includes(r.toLowerCase())).slice(0,Da);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(c=>({name:c.name,full_name:c.metadata.profile?.name||"",reputation:c.reputation,active:c.active}))??[]}})}function Vh(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function zh(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Gn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function je(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await w()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function Zh(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function nw(e="feed"){return queryOptions({queryKey:u.posts.promoted(e),queryFn:async()=>{let t=N.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await w()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function uw(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function fw(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function ww(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function Pw(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function kw(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function te(e){return Array.isArray(e)?e.map(t=>ii(t)):ii(e)}function ii(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function oi(e,t,r){try{let n=await Pt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function si(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return queryOptions({queryKey:u.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let c=await oi(e,i,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return te(p)}let a=n!==void 0?{...s,num:n}:s;return te(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function se(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function ai(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await Wa(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function ui(e,t,r){let n=e.map(nt),i=await Promise.all(n.map(o=>ai(o,t,void 0,r)));return te(i)}async function ci(e,t="",r="",n=20,i="",o="",s){let a=await se("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?ui(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function dr(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await se("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?ui(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function nt(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Wa(e="",t="",r="",n,i){let o=await se("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=nt(o),a=await ai(s,r,n,i);return te(a)}}async function Vw(e="",t=""){let r=await se("get_post_header",{author:e,permlink:t});return r&&nt(r)}async function pi(e,t,r){let n=await se("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=nt(s);return i}return n}async function li(e,t=""){return se("get_community",{name:e,observer:t})}async function jw(e="",t=100,r,n="rank",i=""){return se("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function di(e){let t=await se("normalize_post",{post:e});return t&&nt(t)}async function Lw(e){return se("list_all_subscriptions",{account:e})}async function $w(e){return se("list_subscribers",{community:e})}async function Ww(e,t){return se("get_relationship_between_accounts",[e,t])}async function Tt(e,t){return se("get_profiles",{accounts:e,observer:t})}var mi=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(mi||{});function fr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Ga(e,t,r){let n=l=>fr(l.pending_payout_value).amount+fr(l.author_payout_value).amount+fr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function gi(e,t="created",r=true,n){let i=n||d.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return te(s)},enabled:r&&!!e,select:o=>Ga(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),c=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!c.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function e_(e,t,r,n=true){let i=r||d.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>pi(e,t,i)})}function a_(e,t="posts",r=20,n="",i=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await dr(t,e,o.author??"",o.permlink??"",r,n,s);return te(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function u_(e,t="posts",r="",n="",i=20,o="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await dr(t,e,r,n,i,o,a);return te(c??[])}})}var yi=new Map;function Za(e){let t=yi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>eu(n,e))}),yi.set(e,t)),t}function eu(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function y_(e,t,r=20,n="",i=true,o={}){return infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:c,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return te(p)},select:Za(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function h_(e,t="",r="",n=20,i="",o="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let c=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(c="");let p=await ci(e,t,r,n,c,o,a);return te(p??[])}})}function A_(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function S_(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function R_(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function F_(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function K_(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await w()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function B_(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function wi(e){let r=await w()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function H_(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:wi(t),enabled:!!e&&!!t})}function U_(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:wi(t),enabled:!!e&&!!t})}function V_(e,t,r=10){return infiniteQueryOptions({queryKey:u.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await w()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function W_(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function pu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function Y_(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?pu(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:c,tags:p}=s.list[0];return {body:a,title:c,tags:p}},enabled:i})}function tb(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function du(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function fu(e){return {...e,id:e.id??e.post_id}}function me(e,t){if(!e)return null;let r=e.container??e,n=du(r,t),i=e.parent?fu(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function mu(e){return Array.isArray(e)?e:[]}async function _i(e){let t=gi(e,"created",true),r=await d.queryClient.fetchQuery(t),n=mu(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function bi(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var hu=20;function vi(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??hu}}async function Ai({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let c=N.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=me(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function cb(e={}){let t=vi(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Ai(t,c,p),getNextPageParam:c=>{if(!(c.lengthAi(t,void 0,c)})}var _u=20;function bu(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??_u}}async function vu({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=N.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(i)),o&&c.searchParams.set("cursor",o),e.forEach(f=>c.searchParams.append("container",f)),t&&c.searchParams.set("tag",t),r&&c.searchParams.set("author",r),n&&c.searchParams.set("observer",n);let p=await fetch(c.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=me(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function gb(e={}){let t=bu(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>vu(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await _i(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:bi(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Ab(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await xu(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Su=40;function Sb(e,t,r=Su){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>me(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function Fb(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:u.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>me(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function Kb(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:c,posts:p})=>({tag:c,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function Hb(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:u.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=N.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let c=a.map(p=>me(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function Lb(e){return queryOptions({queryKey:u.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=N.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function Jb(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>di(e)})}function Iu(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Pi(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function iv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Pi(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(si(m.author,m.permlink));Iu(y)&&l.push(y);}let[f]=a;return {lastDate:f?Pi(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function cv(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Tt(e,t)})}function gv(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await ee("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function bv(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ee("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Ov(){return queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function xv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Rv(e,t,r){let n=useQueryClient(),{data:i}=useQuery(M(e));return v(["accounts","update"],e,o=>{let s=Zn(n.getQueryData(M(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ei({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=lr({existingProfile:Xn(a),profile:s.profile,tokens:s.tokens}),c}),await S(t?.adapter,r,[u.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...M(e),staleTime:0});}catch{}}})}function Kv(e,t,r,n,i){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=ri(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await Ln(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(u.accounts.relations(e,t),o),t&&b().invalidateQueries(M(t));}})}function mr(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Ie(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function De(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function gr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function yr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Ke(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Uu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Ke(e,o.trim(),r,n))}function Vu(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function Le(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function Be(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function Oi(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function it(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Be(e,t,r,n,i),Oi(e,i)]}function ot(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function st(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function at(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function ut(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function ct(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function hr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Me(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function wr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function _r(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function br(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function Rt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function ju(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Lu(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return Rt(e,t)}function vr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function Ar(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function Pr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Or(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function xr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function $u(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function Wu(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function Er(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Sr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function kr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Cr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Tr(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Rr(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function Gu(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function zu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var xi=(r=>(r.Buy="buy",r.Sell="sell",r))(xi||{}),Ei=(r=>(r.EMPTY="",r.SWAP="9",r))(Ei||{});function qt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function Ft(e,t=3){return e.toFixed(t)}function Ju(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Ft(t,3)} HBD`:`${Ft(t,3)} HIVE`,p=n==="buy"?`${Ft(r,3)} HIVE`:`${Ft(r,3)} HBD`;return qt(e,c,p,false,s,a)}function Fr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function qr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function Yu(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function Xu(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Ir(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Dr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Kr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Br(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let c={...t,account_auths:a};return c.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:c,memo_key:i,json_metadata:o}]}function Zu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function ec(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function tc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function rc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Mr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Nr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function Qr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function $e(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function nc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>$e(e,o.trim(),r,n))}function Hr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function ic(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function oc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function nA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[br(e,n)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function aA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Rt(e,n)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.relations(e,i.following),u.accounts.full(i.following),u.accounts.followCount(i.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function lA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function gA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function _A(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await w()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:n})}function OA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await w()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:c})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(c);o.setQueryData(c,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(E=>({...E,data:E.data.filter(O=>O.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);s?.previousCheck!==void 0&&a.setQueryData(u.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function dc(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Si(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let c=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=dc(y,n.map((h,E)=>[h[p].createPublic().toString(),E+1])),l};return Z([["account_update",{account:e,json_metadata:r.json_metadata,owner:c("owner"),active:c("active"),posting:c("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function IA(e,t){let{data:r}=useQuery(M(e)),{mutateAsync:n}=Si(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,i,"owner"),active:H.fromLogin(e,i,"active"),posting:H.fromLogin(e,i,"posting"),memo_key:H.fromLogin(e,i,"memo")}]})},...t})}function QA(e,t,r){let n=useQueryClient(),{data:i}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(i.posting));c.account_auths=c.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:c,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return Z([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),jn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(M(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function WA(e,t,r,n){let{data:i}=useQuery(M(e));return useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:c})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await w()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Z([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),jn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function zA(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function ki(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function tP(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=ki(r,o);return Z([["account_update",s]],n)},...t})}function oP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Kr(n,i)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function cP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Br(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function fP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Dr(e,n.newAccountName,n.keys):Ir(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var Ur=300*60*24,Oc=1e4,xc=5e7;function Ci(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,i=C(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Ec(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Sc(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function kc(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=Ci(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Oc/(n*Ur)),a=ur(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-xc,0)}function Cc(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Sc(t))return kc(e,t,n);let i=0;try{if(i=Ci(e),!Number.isFinite(i))return 0}catch{return 0}return Ec(i,r,n)}function hP(e){return ur(e).percentage/100}function wP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*Ur/1e4}function _P(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/Ur;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function bP(e){return xt(e).percentage/100}function vP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let c=Cc(e,t,r,n);return Number.isFinite(c)?c/i*o*(s/a):0}var Tc={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Rc(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Fc(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function qc(e){let t=e[0];return t==="custom_json"?Rc(e):t==="create_proposal"||t==="update_proposal"?Fc(e):Tc[t]??"posting"}function PP(e){let t="posting";for(let r of e){let n=qc(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function kP(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):Qn(r)?n=H.fromString(r):n=H.from(r),Z([t],n)}})}function RP(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function DP(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>jn.sendOperation(t,{callback:e},()=>{})})}function NP(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ti(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Ri(e,t){return {...e??{},title:t.title,body:t.body}}function WP(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await w()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Ri(r,n);i.setQueryData(je(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[o,...a.data]}:a)});}})}function e0(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await w()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ti(s,r,n);i.setQueryData(je(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?o(c):c)}))});}})}function s0(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await w()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData(je(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function G(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function c0(e,t,r,n){let o=await w()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await G(o);return {status:o.status,data:s}}async function p0(e){let r=await w()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await G(r);return {status:r.status,data:n}}async function l0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await w()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await G(s);}async function d0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await w()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(s)}async function f0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},c=await w()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function m0(e,t,r){let n={code:e,username:t,token:r},o=await w()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function Fi(e,t){let r={code:e};t&&(r.id=t);let i=await w()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function qi(e,t){let r={code:e,url:t},i=await w()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}var Uc="https://i.ecency.com";async function Ii(e,t,r){let n=w(),i=new FormData;i.append("file",e);let o=await n(`${Uc}/hs/${t}`,{method:"POST",body:i,signal:r});return G(o)}async function g0(e,t,r,n){let i=w(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return G(s)}async function Di(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Ki(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await w()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(a)}async function Bi(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},c=await w()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function Mi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Ni(e,t,r,n,i,o,s,a){let c={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(c.options=o);let l=await w()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function Qi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Hi(e,t){let r={code:e,id:t},i=await w()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function y0(e,t,r){let n={code:e,author:t,permlink:r},o=await w()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function h0(e,t,r){let n={username:e,email:t,friend:r},o=await w()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}function A0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return Ki(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(u.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function S0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Bi(t,i,o,s,a,c)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function q0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return Mi(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let c=o.getQueryData(s);c&&o.setQueryData(s,c.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(u.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[c,p]of s.previousInfinite)a.setQueryData(c,p);n?.(i);}})}function M0(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Ni(t,i,o,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function V0(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return Qi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function G0(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return Hi(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(u.posts.schedules(e),i):o.invalidateQueries({queryKey:u.posts.schedules(e)}),o.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function Z0(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return qi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function iO(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Di(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],c=>c?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},c=>c&&{...c,pages:c.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function uO(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Ii(r,n,i),onSuccess:e,onError:t})}function Dt(e,t){return `/@${e}/${t}`}function Xc(e,t,r){return (r??b()).getQueryData(u.posts.entry(Dt(e,t)))}function Zc(e,t){(t??b()).setQueryData(u.posts.entry(Dt(e.author,e.permlink)),e);}function It(e,t,r,n){let i=n??b(),o=Dt(e,t),s=i.getQueryData(u.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(u.posts.entry(o),a),s}var Ne;(a=>{function e(c,p,l,f,m){It(c,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(c,p,l,f){It(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){It(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){It(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function i(c,p){c.forEach(l=>Zc(l,p));}a.updateEntries=i;function o(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Dt(c,p))});}a.invalidateEntry=o;function s(c,p,l){return Xc(c,p,l)}a.getEntry=s;})(Ne||={});function ep(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function tp(e,t,r){let n=Ne.getEntry(t.author,t.permlink,r);if(!n?.active_votes||ep(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);Ne.updateVotes(t.author,t.permlink,i,o,r);}function gO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[mr(e,n,i,o)],async(n,i)=>{tp(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function bO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[yr(e,n,i,o??false)],async(n,i)=>{let o=Ne.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));Ne.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${i.author}/${i.permlink}`),u.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function OO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(De(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let c=[u.accounts.full(e),u.resourceCredits.account(e)];if(!o){c.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;c.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(c);}},t,"posting",{broadcastMode:r})}function SO(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function Ui(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[c,p]of a)p&&(s.set(c,p),o.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Vi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function kO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(u.posts.entry(o));return s&&i.setQueryData(u.posts.entry(o),{...s,...r}),s}function CO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(u.posts.entry(o),r);}function IO(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[gr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:c=>{let p=c.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:Ui(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Vi(s);}})}function MO(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;i.push(De(n.author,n.permlink,o,s,a,c,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function UO(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(Ie(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(De(n.author,n.permlink,o,s,a,c,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[u.resourceCredits.account(e)];s.push(u.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,c=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===c}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function $O(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[Qr(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var rp=[3e3,3e3,3e3],np=e=>new Promise(t=>setTimeout(t,e));async function ip(e,t){return g("condenser_api.get_content",[e,t])}async function op(e,t,r=0,n){let i=n?.delays??rp,o;try{o=await ip(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await np(s),op(e,t,r+1,n)}var We={};mt(We,{useRecordActivity:()=>Vr});function ap(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Vr(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=w(),i=ap(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function rx(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function ax(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function lx(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Kt="threespeakfund",hx=1100;function lp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function wx(e,t){if(!lp(t))return e;let r=e.find(n=>n.account===Kt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Kt?{...n,weight:1100}:n):[...e,{account:Kt,weight:1100}]}function _x(e){return e===Kt}var $r={};mt($r,{getAccountTokenQueryOptions:()=>Lr,getAccountVideosQueryOptions:()=>hp});var jr={};mt(jr,{getDecodeMemoQueryOptions:()=>mp});function mp(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new jn.Client({accessToken:r}).decode(t)}})}var ji={queries:jr};function Lr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await w()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=ji.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function hp(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Lr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await w()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var Kx={queries:$r};function Ux(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await w()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function $x({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await w()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function Jx(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function eE(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}var Li={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function nE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Li;let{current_mana:i,max_mana:o}=xt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Li,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,c=s*a,p=i{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function dE(e,t,r,n){let{mutateAsync:i}=Vr(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await w()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function yE(e){let t=e?.replace("@","");return queryOptions({queryKey:u.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await w()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var xp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function wE(e,t){return xp.find(r=>r.tier===e&&r.id===t)}var Ep=25;function Sp(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function _E(e){return Sp(e)>Ep}var bE=300,vE=2;function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function Rp(e){let r=await w()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Tp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function xE(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return Rp(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function CE(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Er(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function qE(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Sr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(i.community)],u.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function BE(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[Rr(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[u.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function HE(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[kr(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===o.account);return p>=0?c[p]=[c[p][0],o.role,c[p][2]??""]:c.push([o.account,o.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function LE(e,t,r,n){return v(["communities","update",e],t,i=>[Cr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function zE(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Hr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(i.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function ZE(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Tr(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${i.account}/${i.permlink}`),[...u.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function iS(e,t,r=100,n=void 0,i=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function cS(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function mS(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>li(e??"",t)})}var $i=100;async function Wi(e,t){return await g("bridge.list_subscribers",{community:e,limit:$i,...t?{last:t}:{}})??[]}function bS(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>Wi(e,null),staleTime:6e4})}function vS(e){return infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Wi(e,t),getNextPageParam:t=>t?.length>=$i?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function SS(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function RS(){return queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var Np=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Np||{}),qS={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function DS(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function KS({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function QS(e,t){return queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function jS(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Up=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(Up||{});var Vp=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))(Vp||{}),Gi=[1,2,3,4,5,6,10,13,15,19,20,21,22],jp=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(jp||{});function YS(e,t,r){return queryOptions({queryKey:u.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Gi]})})}function tk(){return queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function ok(e){return queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function zp(e,t){return {...e,read:!t||t===e.id?1:e.read}}function zi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function dk(e,t,r,n){let i=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Fi(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return zi(f)}});a.forEach(([l,f])=>{if(f&&zi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>zp(h,o)))};i.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=i.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(c,p-1):i.setQueryData(c,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{i.setQueryData(c,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:u.notifications._prefix});}})}function yk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>vr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function bk(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function Tk(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Ct(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function Ik(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function Mk(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[xr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function Uk(e,t,r){return v(["proposals","create"],e,n=>[Or(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function $k(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthee("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function eC(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function iC(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function uC(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function dC(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function yC(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function bC(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function xC(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function CC(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await w()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function qC(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function BC(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function le(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function fl(e){if(!e||typeof e!="object")return;let t=e;return {name:le(t.name)??"",symbol:le(t.symbol)??"",layer:le(t.layer)??"hive",balance:ae(t.balance)??0,fiatRate:ae(t.fiatRate)??0,currency:le(t.currency)??"usd",precision:ae(t.precision)??3,address:le(t.address),error:le(t.error),pendingRewards:ae(t.pendingRewards),pendingRewardsFiat:ae(t.pendingRewardsFiat),liquid:ae(t.liquid),liquidFiat:ae(t.liquidFiat),savings:ae(t.savings),savingsFiat:ae(t.savingsFiat),staked:ae(t.staked),stakedFiat:ae(t.stakedFiat),iconUrl:le(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ae(t.apr)}}function ml(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function gl(e){if(!e||typeof e!="object")return;let t=e;return le(t.username)??le(t.name)??le(t.account)}function Ji(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${N.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=ml(o).map(a=>fl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:gl(o)??e,currency:le(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Bt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(be().queryKey),r=b().getQueryData(M(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function Yi(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(M(e).queryKey),r=b().getQueryData(be().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:C(t.hbd_balance).amount+C(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:C(t.hbd_balance).amount},{name:"savings",balance:C(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function _l(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*c*p/f).toFixed(3)}function Xi(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(be()),await b().prefetchQuery(M(e));let t=b().getQueryData(be().queryKey),r=b().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=C(r.vesting_shares).amount,a=C(r.delegated_vesting_shares).amount,c=C(r.received_vesting_shares).amount,p=C(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=zn(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ue(s,t.hivePerMVests).toFixed(3),y=+Ue(a,t.hivePerMVests).toFixed(3),h=+Ue(c,t.hivePerMVests).toFixed(3),E=+Ue(l,t.hivePerMVests).toFixed(3),O=+Ue(f,t.hivePerMVests).toFixed(3),A=Math.max(m-E,0),P=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+A.toFixed(3),apr:_l(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+P.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...E>0?[{name:"pending_power_down",balance:+E.toFixed(3)}]:[],...O>0&&O!==E?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var K=re.operations,Wr={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay],"":[]};var uT=Object.keys(re.operations);var Zi=re.operations,lT=Zi,dT=Object.entries(Zi).reduce((e,[t,r])=>(e[r]=t,e),{});var eo=re.operations;function vl(e){return Object.prototype.hasOwnProperty.call(eo,e)}function pt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in Wr){Wr[a].forEach(c=>o.add(c));return}vl(a)&&o.add(eo[a]);});let s=Ol(Array.from(o));return {filterKey:i,filterArgs:s}}function Gr(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Al(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Pl(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Ol(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,Pl(Number(s),t),...n])).map(c=>({num:c[0],type:c[1].op[0],timestamp:c[1].timestamp,trx_id:c[1].trx_id,...c[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return C(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=C(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return C(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function PT(e,t=20,r=[]){let{filterKey:n}=pt(r),i=Gr(r);return infiniteQueryOptions({...Mt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return C(c.hbd_payout).amount>0;case "claim_reward_balance":return C(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return C(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=C(c.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(c.type)}}))})})}function kT(e,t=20,r=[]){let{filterKey:n}=pt(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return infiniteQueryOptions({...Mt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(c=>c.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.vesting_payout).amount>0;case "claim_reward_balance":return C(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(C(p.amount).symbol);case "fill_recurrent_transfer":let m=C(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function to(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function zr(e,t){return new Date(e.getTime()-t*1e3)}function FT(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,to(t),to(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[zr(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[zr(n,Math.max(100*e,28800)),zr(n,e)]})}function KT(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function QT(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function LT(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>C(n.vesting_shares).amount-C(r.vesting_shares).amount)})}function zT(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function ZT(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function nR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function aR(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function lR(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=w(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ro(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function gR(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[ro(i),ro(n),e])})}function _R(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function PR(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function SR(e,t,r){return v(["market","limit-order-create"],e,n=>[qt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function RR(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Fr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function lt(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function IR(e,t,r,n){let i=w(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return lt(s)}async function no(e){if(e==="hbd")return 1;let t=w(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await lt(n)).hive_dollar[e]}async function DR(e,t){let n=await w()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return lt(n)}async function KR(){let t=await w()(d.privateApiHost+"/private-api/market-data/latest");return lt(t)}async function BR(){let t=await w()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return lt(t)}var Nl={"Content-type":"application/json"};async function Ql(e){let t=w(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Nl});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function xe(e,t){try{return await Ql(e)}catch{return t}}async function QR(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([xe({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),xe({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((c,p)=>{let l=Number(c.price??0);return Number(p.price??0)-l}),s=a=>a.sort((c,p)=>{let l=Number(c.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function HR(e,t=50){return xe({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function UR(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([xe({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),xe({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),c=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...c].sort((p,l)=>l.timestamp-p.timestamp)}async function Hl(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return xe({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Ge(e,t){return Hl(t,e)}async function Nt(e){return xe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Qt(e){return xe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function io(e,t,r,n){let i=w(),o=N.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function oo(e,t="daily"){let r=w(),n=N.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function so(e){let t=w(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function Ht(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Nt(e)})}function zR(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ge()})}function ao(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Qt(e)})}function rF(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return io(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function sF(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>oo(e,t)})}function pF(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await so(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function uo(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ge(e,t)})}function ze(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,c=typeof a=="string"?parseFloat(a):a;return s+=c.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var Ut=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${ze(this.stake,{fractionDigits:this.precision})} + ${ze(this.delegationsIn,{fractionDigits:this.precision})} - ${ze(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():ze(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():ze(this.balance,{fractionDigits:this.precision})};function vF(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await Nt(e),i=await Qt(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),c=[...s,...a.length?await Ge(void 0,a):[]];return n.map(p=>{let l=i.find(O=>O.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=c.find(O=>O.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),E=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new Ut({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:E})})},enabled:!!e})}function co(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Bt(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(ao([t])),s=await r.ensureQueryData(Ht(e)),a=await r.ensureQueryData(uo(void 0,t)),c=o?.find(O=>O.symbol===t),p=s?.find(O=>O.symbol===t),f=+(a?.find(O=>O.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),E=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&E.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:E}}})}function dt(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function po(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(dt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(dt(e).queryKey)?.points??0)})})}function NF(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function YF(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await no(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=Ji(e,i,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let O=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let A=Math.abs(Number.parseFloat(O[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:A}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:A}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:A});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Bt(e));else if(t==="HP")l=await o(Xi(e));else if(t==="HBD")l=await o(Yi(e));else if(t==="POINTS")l=await o(po(e));else if((await n.ensureQueryData(Ht(e))).some(m=>m.symbol===t))l=await o(co(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var td=(A=>(A.Transfer="transfer",A.TransferToSavings="transfer-saving",A.WithdrawFromSavings="withdraw-saving",A.Delegate="delegate",A.PowerUp="power-up",A.PowerDown="power-down",A.WithdrawRoutes="withdraw-routes",A.ClaimInterest="claim-interest",A.Swap="swap",A.Convert="convert",A.Gift="gift",A.Promote="promote",A.Claim="claim",A.Buy="buy",A.Stake="stake",A.Unstake="unstake",A.Undelegate="undelegate",A))(td||{});function nq(e,t,r){return v(["wallet","transfer"],e,n=>[Ke(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function uq(e,t,r){return v(["wallet","transfer-point"],e,n=>[$e(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function fq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[at(e,n.delegatee,n.vestingShares)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[ut(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await S(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function Aq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Sq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Le(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Fq(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Be(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Bq(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[ot(e,n.to,n.amount)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Uq(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[st(e,n.vestingShares)],async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Wq(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?hr(e,n.amount,n.requestId):ct(e,n.amount,n.requestId)],async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Xq(e,t,r){return v(["wallet","claim-interest"],e,n=>it(e,n.to,n.amount,n.memo,n.requestId),async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var rd=5e3,Vt=new Map;function nI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[qr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],u.assets.hiveGeneralInfo(e),u.assets.hbdGeneralInfo(e),u.assets.hivePowerGeneralInfo(e)],o=Vt.get(n);o&&(clearTimeout(o),Vt.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Vt.delete(n);}},rd);Vt.set(n,s);},t,"posting",{broadcastMode:r})}function aI(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function lI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _I(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PI(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function SI(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nd(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Ke(n,i,o,s)];case "transfer-saving":return [Le(n,i,o,s)];case "withdraw-saving":return [Be(n,i,o,s,a)];case "power-up":return [ot(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Ke(n,i,o,s)];case "transfer-saving":return [Le(n,i,o,s)];case "withdraw-saving":return [Be(n,i,o,s,a)];case "claim-interest":return it(n,i,o,s,a);case "convert":return [ct(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [st(n,o)];case "delegate":return [at(n,i,o)];case "withdraw-routes":return [ut(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [$e(n,i,o,s)];break}return null}function id(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [Me(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [Me(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [Me(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [Me(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [Me(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [wr(n,[e])]}return null}function od(e){return e==="claim"?"posting":"active"}function qI(e,t,r,n,i){let{mutateAsync:o}=We.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=nd(t,r,s);if(a)return a;let c=id(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,od(r),{broadcastMode:i})}function BI(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[_r(e,n,i)],async(n,i)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(i.to),u.resourceCredits.account(e),u.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function HI(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[Ar(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function LI(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Pr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function ad(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function YI(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ee("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(ad),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function XI(e,t,r,n="vests",i="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await ee("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function ZI(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await ee("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var ud=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(ud||{});async function pd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await w()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function sD(e,t,r,n){let{mutateAsync:i}=We.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>pd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(dt(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var fo=/(^|\s)author:([^\s]+)/g,mo=/(^|\s)type:([^\s]+)/g,go=/(^|\s)category:([^\s]+)/g,yo=/(^|\s)tag:([^\s]+)/g;var wo=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(wo||{}),uD=5,cD=100;function _o(e){return e.trim().split(/\s+/)[0]??""}function ld(e){return _o(e).replace(/^@+/,"").toLowerCase()}function dd(e){return _o(e).replace(/^#+/,"").toLowerCase()}function fd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function pD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=ld(t),a=dd(n),c=fd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),c.length>0&&p.push(`tag:${c.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:c}}var ho=class{query="";search="";author="";type="";category="";tags=[];constructor(t){this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}grab=t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""};grabAuthor=()=>{this.author=this.grab(fo);};grabType=()=>{let t=this.grab(mo);Object.values(wo).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(go);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(yo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([fo,mo,go,yo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();}};async function ve(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Ee(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var gd=isServer?0:3;function ft(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let c=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(_e,s)});return ve(c,Ee)},retry:ft})}function vD(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:c,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:we(_e,i)});return ve(y,Ee)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:ft})}async function xD(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await w()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(_e,s)});return ve(p,Ee)}async function bo(e,t,r=_e){let i=await w()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:we(r,t)});return ve(i,Ee)}async function ED(e,t){let n=await w()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:we(_e,t)}),i=await ve(n,Array.isArray);return i?.length>0?i:[e]}var _d=4368*60*60*1e3,bd=4,vd=3e3,Ad=2e3,Pd=4e3,RD=2;function Od(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function xd(e){let t=5381;for(let r=0;r>>0).toString(36)}function FD(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Od(e.body??"",vd),o=xd(`${t}|${n.join(",")}|${i}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-_d).toISOString().slice(0,19),c=await bo({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?Ad:Pd),p=[],l=new Set;for(let f of c.results){if(p.length>=bd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function MD(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Tt(n)},enabled:!!r})}function VD(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function zD(e,t,r,n,i,o){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),i!==void 0&&(c.votes=i),o&&(c.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(c),signal:we(_e,a)});return ve(p,Ee)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:ft})}function ZD(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function Rd(e){let r=await w()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function nK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Rd(t)},enabled:!!r&&!!t})}async function Id(e,t){let n=await w()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Dd(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function uK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Id(t,i)},onSuccess(i){n&&Dd(r,n,i);}})}function dK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function yK(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function bK(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function OK(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function kK(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function FK(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[Mr(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function KK(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Nr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function NK(e){let r=await w()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var Ud="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function VK(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Ud,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` -`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var LK=1.1,Vd=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Vd||{});function $K(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function $d(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let c=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:c?{total_votes:c.total_votes??0,hive_hp:c.hive_hp,hive_proxied_hp:c.hive_proxied_hp,hive_hp_incl_proxied:c.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function YK(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?$n:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=w(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return $d(o[0])}})}function eB(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** +import {useQuery,useInfiniteQuery,useMutation,QueryClient,queryOptions,infiniteQueryOptions,useQueryClient,isServer}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import an from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import Gn from'hivesigner';var So=Object.defineProperty;var ht=(e,t)=>{for(var r in t)So(e,r,{get:t[r],enumerable:true});};var _t=new ArrayBuffer(0),wt=null,bt=null;function ko(){return wt||(typeof TextEncoder<"u"?wt=new TextEncoder:wt={encode(e){let t=[];for(let r=0;r>6,128|n&63);else if(n>=55296&&n<=56319&&r+1>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),wt}function en(){return bt||(typeof TextDecoder<"u"?bt=new TextDecoder:bt={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n>10),56320+(o&1023)));}return r}}),bt}var I=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?_t:new ArrayBuffer(t),this.view=t===0?new DataView(_t):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(_t));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i;return t instanceof e?(i=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=i.length):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t),i.length<=0?this:(r+i.length>this.buffer.byteLength&&this.resize(r+i.length),new Uint8Array(this.buffer).set(i,r),n&&(this.offset+=i.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,i=new e(n,this.littleEndian);return i.offset=0,i.limit=n,new Uint8Array(i.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),i}copyTo(t,r,n,i){let o=typeof r>"u",s=typeof n>"u";r=o?t.offset:r,n=s?this.offset:n,i=i===void 0?this.limit:i;let a=i-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,i),r),s&&(this.offset+=a),o&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return rt?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?_t:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=this.calculateVarint32(t);for(r+i>this.buffer.byteLength&&this.resize(r+i),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):i}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,i=0,o;do o=this.view.getUint8(t++),n<5&&(i|=(o&127)<<7*n),++n;while((o&128)!==0);return i|=0,r?(this.offset=t,i):{value:i,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",i=n?this.offset:r,o=ko().encode(t),s=o.length,a=this.calculateVarint32(s);return i+a+s>this.buffer.byteLength&&this.resize(i+a+s),this.writeVarint32(s,i),i+=a,new Uint8Array(this.buffer).set(o,i),i+=s,n?(this.offset=i,this):i-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,i=this.readVarint32(t),o=i.value,s=i.length;t+=s;let a=en().decode(new Uint8Array(this.buffer,t,o));return t+=o,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let i=en().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,i):{string:i,length:t}}};var E={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},zt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Jt=e=>{let t=zt(e);t.length&&(E.nodes=t);},Yt=e=>{let t=zt(e);t.length&&(E.restNodes=t);},Xt=e=>{if(!e||typeof e!="object")return;let t={...E.restNodesByApi};for(let[r,n]of Object.entries(e)){let i=zt(n);i.length?t[r]=i:delete t[r];}E.restNodesByApi=t;},Zt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(E.userAgent=t);},er=e=>{if(!e||typeof e!="object")return;let t=E.resilience,r=i=>typeof i=="boolean",n=i=>typeof i=="number"&&Number.isFinite(i)&&i>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var Pe=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,i=true;n<0&&(i=false,n=n+4);let o=r.subarray(1);return new e(o,n,i)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new J(n.recoverPublicKey(t).toBytes())}};var J=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??E.address_prefix;}static fromString(t){let r=E.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let i;try{i=an.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(i.length!==37)throw new Error("Invalid public key length");let o=i.subarray(0,33),s=i.subarray(33,37),a=ripemd160(o).subarray(0,4);if(!To(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(o);}catch{throw new Error("Invalid public key")}return new e(o,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Pe.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Co(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Co=(e,t)=>{let r=ripemd160(e);return t+an.encode(new Uint8Array([...e,...r.subarray(0,4)]))},To=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},w=(e,t)=>{e.writeVString(t);},qo=(e,t)=>{e.writeInt16(t);},un=(e,t)=>{e.writeInt64(t);},cn=(e,t)=>{e.writeUint8(t);},ce=(e,t)=>{e.writeUint16(t);},Y=(e,t)=>{e.writeUint32(t);},pn=(e,t)=>{e.writeUint64(t);},ye=(e,t)=>{e.writeByte(t?1:0);},ln=e=>(t,r)=>{let[n,i]=r;t.writeVarint32(n),e[n](t,i);},q=(e,t)=>{let r=vt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let i=0;i<7;i++)e.writeUint8(r.symbol.charCodeAt(i)||0);},Oe=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},fe=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(J.from(t).key);},dn=(e=null)=>(t,r)=>{r=At.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},fn=dn(),tr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[i,o]of n)e(r,i),t(r,o);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ue=e=>(t,r)=>{for(let[n,i]of e)try{i(t,r[n]);}catch(o){throw o.message=`${n}: ${o.message}`,o}},Ce=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=ue([["weight_threshold",Y],["account_auths",tr(w,ce)],["key_auths",tr(fe,ce)]]),Io=ue([["account",w],["weight",ce]]),rr=ue([["base",q],["quote",q]]),Do=ue([["account_creation_fee",q],["maximum_block_size",Y],["hbd_interest_rate",ce]]),R=(e,t)=>{let r=ue(t);return (n,i)=>{n.writeVarint32(e),r(n,i);}},k={};k.account_create=R(T.account_create,[["fee",q],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w]]);k.account_create_with_delegation=R(T.account_create_with_delegation,[["fee",q],["delegation",q],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w],["extensions",V(ie)]]);k.account_update=R(T.account_update,[["account",w],["owner",Ce(W)],["active",Ce(W)],["posting",Ce(W)],["memo_key",fe],["json_metadata",w]]);k.account_witness_proxy=R(T.account_witness_proxy,[["account",w],["proxy",w]]);k.account_witness_vote=R(T.account_witness_vote,[["account",w],["witness",w],["approve",ye]]);k.cancel_transfer_from_savings=R(T.cancel_transfer_from_savings,[["from",w],["request_id",Y]]);k.change_recovery_account=R(T.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",V(ie)]]);k.claim_account=R(T.claim_account,[["creator",w],["fee",q],["extensions",V(ie)]]);k.claim_reward_balance=R(T.claim_reward_balance,[["account",w],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);k.comment=R(T.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);k.comment_options=R(T.comment_options,[["author",w],["permlink",w],["max_accepted_payout",q],["percent_hbd",ce],["allow_votes",ye],["allow_curation_rewards",ye],["extensions",V(ln([ue([["beneficiaries",V(Io)]])]))]]);k.convert=R(T.convert,[["owner",w],["requestid",Y],["amount",q]]);k.create_claimed_account=R(T.create_claimed_account,[["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",fe],["json_metadata",w],["extensions",V(ie)]]);k.custom=R(T.custom,[["required_auths",V(w)],["id",ce],["data",fn]]);k.custom_json=R(T.custom_json,[["required_auths",V(w)],["required_posting_auths",V(w)],["id",w],["json",w]]);k.decline_voting_rights=R(T.decline_voting_rights,[["account",w],["decline",ye]]);k.delegate_vesting_shares=R(T.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",q]]);k.delete_comment=R(T.delete_comment,[["author",w],["permlink",w]]);k.escrow_approve=R(T.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Y],["approve",ye]]);k.escrow_dispute=R(T.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",Y]]);k.escrow_release=R(T.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",Y],["hbd_amount",q],["hive_amount",q]]);k.escrow_transfer=R(T.escrow_transfer,[["from",w],["to",w],["hbd_amount",q],["hive_amount",q],["escrow_id",Y],["agent",w],["fee",q],["json_meta",w],["ratification_deadline",Oe],["escrow_expiration",Oe]]);k.feed_publish=R(T.feed_publish,[["publisher",w],["exchange_rate",rr]]);k.limit_order_cancel=R(T.limit_order_cancel,[["owner",w],["orderid",Y]]);k.limit_order_create=R(T.limit_order_create,[["owner",w],["orderid",Y],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",ye],["expiration",Oe]]);k.limit_order_create2=R(T.limit_order_create2,[["owner",w],["orderid",Y],["amount_to_sell",q],["exchange_rate",rr],["fill_or_kill",ye],["expiration",Oe]]);k.recover_account=R(T.recover_account,[["account_to_recover",w],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);k.request_account_recovery=R(T.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",W],["extensions",V(ie)]]);k.reset_account=R(T.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",W]]);k.set_reset_account=R(T.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);k.set_withdraw_vesting_route=R(T.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",ce],["auto_vest",ye]]);k.transfer=R(T.transfer,[["from",w],["to",w],["amount",q],["memo",w]]);k.transfer_from_savings=R(T.transfer_from_savings,[["from",w],["request_id",Y],["to",w],["amount",q],["memo",w]]);k.transfer_to_savings=R(T.transfer_to_savings,[["from",w],["to",w],["amount",q],["memo",w]]);k.transfer_to_vesting=R(T.transfer_to_vesting,[["from",w],["to",w],["amount",q]]);k.vote=R(T.vote,[["voter",w],["author",w],["permlink",w],["weight",qo]]);k.withdraw_vesting=R(T.withdraw_vesting,[["account",w],["vesting_shares",q]]);k.witness_update=R(T.witness_update,[["owner",w],["url",w],["block_signing_key",fe],["props",Do],["fee",q]]);k.witness_set_properties=R(T.witness_set_properties,[["owner",w],["props",tr(w,fn)],["extensions",V(ie)]]);k.account_update2=R(T.account_update2,[["account",w],["owner",Ce(W)],["active",Ce(W)],["posting",Ce(W)],["memo_key",Ce(fe)],["json_metadata",w],["posting_json_metadata",w],["extensions",V(ie)]]);k.create_proposal=R(T.create_proposal,[["creator",w],["receiver",w],["start_date",Oe],["end_date",Oe],["daily_pay",q],["subject",w],["permlink",w],["extensions",V(ie)]]);k.update_proposal_votes=R(T.update_proposal_votes,[["voter",w],["proposal_ids",V(un)],["approve",ye],["extensions",V(ie)]]);k.remove_proposal=R(T.remove_proposal,[["proposal_owner",w],["proposal_ids",V(un)],["extensions",V(ie)]]);var Ko=ue([["end_date",Oe]]);k.update_proposal=R(T.update_proposal,[["proposal_id",pn],["creator",w],["daily_pay",q],["subject",w],["permlink",w],["extensions",V(ln([ie,Ko]))]]);k.collateralized_convert=R(T.collateralized_convert,[["owner",w],["requestid",Y],["amount",q]]);k.recurrent_transfer=R(T.recurrent_transfer,[["from",w],["to",w],["amount",q],["memo",w],["recurrence",ce],["executions",ce],["extensions",V(ue([["type",cn],["value",ue([["pair_id",cn]])]]))]]);var Bo=(e,t)=>{let r=k[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},No=ue([["ref_block_num",ce],["ref_block_prefix",Y],["expiration",Oe],["operations",V(Bo)],["extensions",V(w)]]),Mo=ue([["from",fe],["to",fe],["nonce",pn],["check",Y],["encrypted",dn()]]),pe={Asset:q,Memo:Mo,Price:rr,PublicKey:fe,String:w,Transaction:No,UInt16:ce,UInt32:Y};var tt=e=>new Promise(t=>setTimeout(t,e));var Qo=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function hn(){return Qo?{"User-Agent":E.userAgent}:{}}var X=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},Te=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function _n(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var Ho=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Uo=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Vo(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function jo(e){if(!e)return false;if(e instanceof Te)return true;if(e instanceof X)return false;let t=Vo(e);return !!(Ho.some(r=>t.includes(r))||Uo.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function nr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function wn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Lo=1e4,$o=6e4,Wo=12e4,mn=2,gn=6e4,yn=12e4,Go=30,rt=.3,ir=3,nt=5*6e4,bn=6e4,vn=1e3,An=2e3,Ot=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,i){let o=this.getOrCreate(t);if(o.consecutiveFailures=0,o.rateLimitStreak=0,r){let s=o.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&o.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(o,n,i??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=ir&&i-o.updatedAt<=nt?o.ewmaMs:void 0}return this.isLatencyUsable(n,i)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let i=Date.now();if(t.latencyUpdatedAt>0&&i-t.latencyUpdatedAt>nt&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:rt*r+(1-rt)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=i,n!==void 0){let o=t.apiLatency.get(n);!o||i-o.updatedAt>nt?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:i}):(o.ewmaMs=rt*r+(1-rt)*o.ewmaMs,o.sampleCount++,o.updatedAt=i);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(o.cooldownUntil>0&&o.cooldownUntil<=i||o.lastFailureTime>0&&i-o.lastFailureTime>3e4)&&(o.count=0,o.cooldownUntil=0),o.count++,o.lastFailureTime=i,o.count>=mn&&(o.cooldownUntil=i+gn),n.apiFailures.set(r,o);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),i=Date.now(),o=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};o.count=Math.max(o.count+1,mn),o.lastFailureTime=i,o.cooldownUntil=i+gn,o.defective=true,n.apiFailures.set(r,o);}recordRateLimit(t,r){let n=this.getOrCreate(t),i=Date.now();n.rateLimitStreak>0&&i-n.lastRateLimitAt>Wo&&(n.rateLimitStreak=0);let o=typeof r=="number"&&Number.isFinite(r)&&r>0,s=o?r:Math.min(Lo*2**n.rateLimitStreak,$o);o||n.rateLimitStreak++,n.lastRateLimitAt=i,n.rateLimitedUntil=o?i+s:Math.max(n.rateLimitedUntil,i+s),n.consecutiveFailures++,n.lastFailureTime=i;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=yn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,i)=>n-i),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let i=Date.now();if(n.rateLimitedUntil>i||n.consecutiveFailures>=3&&i-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>i)return false}let o=this.consensusHeadBlock();return !(o>0&&n.headBlock>0&&i-n.headBlockUpdatedAt<=yn&&o-n.headBlock>Go)}getOrderedNodes(t,r){let n=[],i=[];for(let u of t)this.isNodeHealthy(u,r)?n.push(u):i.push(u);if(n.length<=1)return [...n,...i];let o=Date.now(),s=n.map((u,p)=>({node:u,i:p,score:this.scoreNode(u,o)})).sort((u,p)=>u.score-p.score||u.i-p.i).map(u=>u.node),a=this.pickReprobeCandidate(n,o);return a&&s[0]!==a?[a,...s.filter(u=>u!==a),...i]:[...s,...i]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=ir&&r-t.latencyUpdatedAt<=nt}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:vn}pickReprobeCandidate(t,r){let n=r-bn,i,o=1/0;for(let s of t){let a=this.getOrCreate(s),u=Math.max(a.latencyUpdatedAt,a.lastProbeAt);u<=n&&u=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(E.resilience.hedgeBucketCapacity,this.tokens+E.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>E.resilience.hedgeBucketCapacity&&(this.tokens=E.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=E.resilience.hedgeBucketCapacity){this.tokens=t;}},sr=new or;function xt(e,t,r,n,i){let o=E.resilience;if(!o.adaptiveTimeout||i)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(o.adaptiveTimeoutFloorMs,o.adaptiveTimeoutFactor*s)))}function ar(e,t,r,n){r instanceof Te?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof X?e.recordFailure(t,n):e.recordFailure(t);}function Pn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let i=n.head_block_number;typeof i=="number"&&e.recordHeadBlock(t,i);}function zo(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function On(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(zo()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function cr(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),i=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",i,{once:true});let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i);};return {signal:r.signal,cleanup:o}}var it=async(e,t,r,n=E.timeout,i=false,o)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:u,cleanup:p}=On(n),{signal:l,cleanup:f}=cr(u,o),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...hn()},signal:l});if(y.status===429)throw new Te(e,"HTTP 429 Rate Limited",{rateLimitMs:_n(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new Te(e,`HTTP ${y.status} from ${e}`);let h=await y.json();if(!h||typeof h.id>"u"||h.id!==s||h.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in h)return h.result;if("error"in h){let O=h.error;throw "message"in O&&"code"in O?new X(O):h.error}throw h}catch(y){if(y instanceof X||y instanceof Te||o?.aborted)throw y;if(i)return it(e,t,r,n,false,o);throw y}finally{m();}};function Pt(){return tt(50+Math.random()*50)}function Jo(e){let{method:t,params:r,api:n,primary:i,hedgePool:o,callerTimeout:s,explicitTimeout:a,deadlineAt:u,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let h=false,O=0,x=false,A=false,P,L,U=0,B=[],Q=z=>{if(!h){h=true,L!==void 0&&(clearTimeout(L),L=void 0);for(let F of B)F.signal.aborted||F.abort();z();}},$=(z,F)=>{O++;let de=new AbortController;B.push(de);let et=cr(de.signal,p),Eo=xt(j,z,t,s,a),Gt=Date.now();F||(U=Gt),it(z,t,r,Eo,false,et.signal).then(ne=>{if(et.cleanup(),O--,F||(A=true),!h){if(f&&!f(ne)){if(j.recordDefectiveResponse(z,n),P=new Error(`[hive-tx] response validation failed for ${t} from ${z}`),!F&&!x){Q(()=>y(P));return}O===0&&Q(()=>y(P));return}j.recordSuccess(z,n,Date.now()-Gt,t),Pn(j,z,t,ne),F?A||j.recordCensoredLatency(i,Date.now()-U,t):x||sr.refill(),Q(()=>m(ne));}}).catch(ne=>{if(et.cleanup(),O--,F||(A=true),!h){if(p?.aborted){Q(()=>y(ne));return}if(ne instanceof X&&!nr(ne.code,ne.message)){Q(()=>y(ne));return}if(ar(j,z,ne,n),j.recordSlowFailure(z,Date.now()-Gt,t),P=ne,!F&&!x){Q(()=>y(ne));return}O===0&&Q(()=>y(P));}});};$(i,false);let ke=j.getUsableLatencyMs(i,t)??0,Ze=xt(j,i,t,s,a),Wt=Math.min(Math.max(E.resilience.hedgeDelayFloorMs,E.resilience.hedgeDelayFactor*ke),.8*Ze);L=setTimeout(()=>{if(L=void 0,h||p?.aborted||Date.now()>=u)return;let z=o.filter(de=>j.isNodeHealthy(de,n));if(z.length===0)return;let F=z[Math.floor(Math.random()*z.length)];sr.trySpend()&&(x=true,l(F),$(F,true));},Wt);})}var g=async(e,t=[],r,n=E.retry,i,o)=>{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??E.timeout,u=wn(e),p=Date.now()+E.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=j.getOrderedNodes(E.nodes,u),h=y.find(A=>!l.has(A));h||(l.clear(),h=y[0]),l.add(h);let O=[];if(E.resilience.hedge&&j.getUsableLatencyMs(h,e)!==void 0&&(O=y.filter(A=>!l.has(A)&&j.isNodeHealthy(A,u)).slice(0,3)),O.length>0)try{return await Jo({method:e,params:t,api:u,primary:h,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:i,onHedgeFired:A=>l.add(A),validate:o})}catch(A){if(A instanceof X&&!nr(A.code,A.message)||i?.aborted)throw A;f=A,m{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an array");if(E.nodes.length===0)throw new Error("config.nodes is empty");let i=wn(e),o=new Set,s;for(let a=0;a!o.has(l));if(!p)break;if(o.add(p),n?.aborted)throw new Error("Aborted");try{let l=await it(p,e,t,r,!1,n);return j.recordSuccess(p,i),l}catch(l){if(l instanceof X||n?.aborted||(ar(j,p,l,i),s=l,!jo(l)))throw l}}throw s},Yo={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function ee(e,t,r,n,i=E.retry,o){if(!Array.isArray(E.restNodes))throw new Error("config.restNodes is not an array");if(E.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??E.timeout,u=Date.now()+E.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=E.restNodesByApi?.[e]?.length?E.restNodesByApi[e]:E.restNodes,f=new Set,m,y=false;for(let h=0;h<=i&&!(h>0&&Date.now()>=u);h++){let O=xe.getOrderedNodes(l,e),x=O.find(F=>!f.has(F));x||(f.clear(),x=O[0]),f.add(x);let A=x+Yo[e],P=t,L=r||{},U=new Set;Object.entries(L).forEach(([F,de])=>{P.includes(`{${F}}`)&&(P=P.replace(`{${F}}`,encodeURIComponent(String(de))),U.add(F));});let B=new URL(A+P);if(Object.entries(L).forEach(([F,de])=>{U.has(F)||(Array.isArray(de)?de.forEach(et=>B.searchParams.append(F,String(et))):B.searchParams.set(F,String(de)));}),o?.aborted)throw new Error("Aborted");y=false;let{signal:Q,cleanup:$}=On(xt(xe,x,p,a,s)),{signal:ke,cleanup:Ze}=cr(Q,o),Wt=()=>{$(),Ze();},z=Date.now();try{let F=await fetch(B.toString(),{signal:ke,headers:hn()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw xe.recordRateLimit(x,_n(F.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${x}`);if(F.status===503)throw xe.recordFailure(x,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${x}`);if(!F.ok)throw xe.recordFailure(x,e),y=!0,new Error(`HTTP ${F.status} from ${x}`);return xe.recordSuccess(x,e,Date.now()-z,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||o?.aborted)throw F;y||xe.recordFailure(x,e),xe.recordSlowFailure(x,Date.now()-z,p),m=F,h{if(!Array.isArray(E.nodes))throw new Error("config.nodes is not an Array");if(r>E.nodes.length)throw new Error("quorum > config.nodes.length");let o=(u=>{let p=[...u];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(E.nodes),s=Math.min(r,o.length),a=[];for(;s>0&&o.length>0;){let u=o.splice(0,s),p=[],l=[];for(let m=0;ml.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Xo(a,r);if(f)return f;if(s=Math.min(r,o.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Xo(e,t){let r=new Map;for(let i of e){let o=JSON.stringify(i);r.has(o)||r.set(o,[]),r.get(o).push(i);}let n=Array.from(r.values()).find(i=>i.length>=t);return n?n[0]:null}var es=hexToBytes(E.chain_id),Re=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let i of t){let o=i.sign(r);this.transaction.signatures.push(o.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await He("condenser_api.broadcast_transaction",[this.transaction]);}catch(o){if(!(o instanceof X&&o.message.includes("Duplicate transaction check failed")))throw o}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await tt(1e3);let n=await this.checkStatus(),i=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&i{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),i=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),o=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:o,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:i,signatures:[]};}};var Tn=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(is(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=hexToBytes(t);else {let n=[];for(let i=0;i>6,128|o&63);else if(o>=55296&&o<=56319&&i+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else n.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let i=t+n+r;return e.fromSeed(i)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return Pe.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new J(secp256k1.getPublicKey(this.key),t)}toString(){return ns(new Uint8Array([...Tn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},Rn=e=>sha256(sha256(e)),ns=e=>{let t=Rn(e);return an.encode(new Uint8Array([...e,...t.slice(0,4)]))},is=e=>{let t=an.decode(e);if(!kn(t.slice(0,1),Tn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),i=Rn(n).slice(0,4);if(!kn(r,i))throw new Error("Private key checksum mismatch");return n},kn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nDn(e,t,n,r),In=(e,t,r,n,i)=>Dn(e,t,r,n,i).message,Dn=(e,t,r,n,i)=>{let o=r,s=e.getSharedSecret(t),a=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);a.writeUint64(o),a.append(s),a.flip();let u=sha512(new Uint8Array(a.toBuffer())),p=u.subarray(32,48),l=u.subarray(0,32),f=sha256(u).subarray(0,4),m=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(i!==void 0){if(y!==i)throw new Error("Invalid key");n=cs(n,l,p);}else n=us(n,l,p);return {nonce:o,message:n,checksum:y}},cs=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},us=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},pr=null,ps=()=>{if(pr===null){let r=secp256k1.utils.randomSecretKey();pr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++pr%65536;return e=e<{let t=ys(e,33);return new J(t)},ds=e=>e.readUint64(),fs=e=>e.readUint32(),ms=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},gs=e=>t=>{let r={},n=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);n.append(t),n.flip();for(let[i,o]of e)try{r[i]=o(n);}catch(s){throw s.message=`${i}: ${s.message}`,s}return r};function ys(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var hs=gs([["from",Kn],["to",Kn],["nonce",ds],["check",fs],["encrypted",ms]]),Bn={Memo:hs};var Mn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Hn(),e=Un(e),t=_s(t);let i=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);i.writeVString(r);let o=new Uint8Array(i.copy(0,i.offset).toBuffer()),{nonce:s,message:a,checksum:u}=qn(e,t,o,n),p=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);pe.Memo(p,{check:u,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+an.encode(l)},Qn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Hn(),e=Un(e);let r=Bn.Memo(an.decode(t)),{from:n,to:i,nonce:o,check:s,encrypted:a}=r,p=e.createPublic().toString()===new J(n.key).toString()?new J(i.key):new J(n.key);r=In(e,p,o,a,s);let l=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},St,Hn=()=>{if(St===void 0){let e;St=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Mn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Qn(t,n);}finally{St=e==="#memo\u7231";}}if(St===false)throw new Error("This environment does not support encryption.")},Un=e=>typeof e=="string"?H.fromString(e):e,_s=e=>typeof e=="string"?J.fromString(e):e,Vn={decode:Qn,encode:Mn};var re={};ht(re,{buildWitnessSetProperties:()=>Os,makeBitMaskFilter:()=>As,operations:()=>vs,validateUsername:()=>bs});var bs=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),i=n.length;for(let o=0;oe.reduce(Ps,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),Ps=([e,t],r)=>r<64?[e|BigInt(1)<{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let i;switch(n){case "key":case "new_signing_key":i=pe.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":i=pe.UInt32;break;case "hbd_interest_rate":i=pe.UInt16;break;case "url":i=pe.String;break;case "hbd_exchange_rate":i=pe.Price;break;case "account_creation_fee":i=pe.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,xs(i,t[n])]);}return r.props.sort((n,i)=>n[0].localeCompare(i[0])),["witness_set_properties",r]},xs=(e,t)=>{let r=new I(I.DEFAULT_CAPACITY,I.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function Pm(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|i&63);else if(i>=55296&&i<=56319&&n+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else r.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function jn(e){try{return H.fromString(e),!0}catch{return false}}async function Z(e,t){let r=new Re;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),He("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Ln(e,t){let r=new Re;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var Ss=432e3;function $n(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/Ss,i=Math.round(n/e*1e4);return !isFinite(i)||i<0?i=0:i>1e4&&(i=1e4),{current_mana:n,max_mana:e,percentage:i}}function ks(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),i=parseFloat(e.vesting_withdraw_rate),o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t-s-r+n}function lr(e){let t=ks(e)*1e6;return $n(t,e.voting_manabar)}function kt(e){return $n(Number(e.max_rc),e.rc_manabar)}var Wn=(u=>(u.COMMON="common",u.INFO="info",u.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",u.MISSING_AUTHORITY="missing_authority",u.TOKEN_EXPIRED="token_expired",u.NETWORK="network",u.TIMEOUT="timeout",u.VALIDATION="validation",u))(Wn||{});function Ue(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",i=t||r||String(e||""),o=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||i&&a.test(i));if(o(/please wait to transact/i)||o(/insufficient rc/i)||o(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(o(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(o(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(o(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(o(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(o(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(o(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(o(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(o(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(o(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(o(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(o(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(o(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||o(/token expired/i)||o(/invalid token/i)||o(/\bunauthorized\b/i)||o(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(o(/has already reblogged/i)||o(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(o(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(o(/econnrefused/i)||o(/connection refused/i)||o(/failed to fetch/i)||o(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(o(/timeout/i)||o(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(o(/account.*does not exist/i)||o(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(o(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(o(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(o(/\b(invalid|validation)\b/i))return {message:(e?.message||i).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:i&&i!=="[object Object]"?s=i.substring(0,150):s="Unknown error occurred":s=i.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Cs(e){let t=Ue(e);return [t.message,t.type]}function he(e){let{type:t}=Ue(e);return t==="missing_authority"||t==="token_expired"}function Ts(e){let{type:t}=Ue(e);return t==="insufficient_resource_credits"}function Rs(e){let{type:t}=Ue(e);return t==="info"}function Fs(e){let{type:t}=Ue(e);return t==="network"||t==="timeout"}async function _e(e,t,r,n,i="posting",o,s,a="async"){let u=n?.adapter;switch(e){case "key":{if(!u)throw new Error("No adapter provided for key-based auth");let p=o;if(p===void 0)switch(i){case "owner":if(u.getOwnerKey)p=await u.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":u.getActiveKey&&(p=await u.getActiveKey(t));break;case "memo":if(u.getMemoKey)p=await u.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await u.getPostingKey(t);break}if(!p)throw new Error(`No ${i} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Ln(r,l):await Z(r,l)}case "hiveauth":{if(!u?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await u.broadcastWithHiveAuth(t,r,i)}case "hivesigner":{if(!u)throw new Error("No adapter provided for HiveSigner auth");if(i!=="posting"){if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`HiveSigner access token cannot sign ${i} operations. No platform broadcast available.`)}let p=s!==void 0?s:await u.getAccessToken(t);if(p)try{return (await new Gn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(u.broadcastWithHiveSigner&&he(l))return await u.broadcastWithHiveSigner(t,r,i);throw l}if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,i);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!u?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await u.broadcastWithKeychain(t,r,i)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,i)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Is(e,t,r,n="posting",i="async"){let o=r?.adapter;if(o?.getLoginType){let l=await o.getLoginType(e,n);if(l){let f=o.hasPostingAuthorization?await o.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(m){if(!he(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await _e(l,e,t,r,n,void 0,void 0,i)}catch(m){if(he(m)&&o.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",h=await o.showAuthUpgradeUI(n,y);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(h,e,t,r,n,void 0,void 0,i)}throw m}}if(n==="posting")try{return await _e("hivesigner",e,t,r,n,void 0,void 0,i)}catch(f){if(he(f)&&o.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await o.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await _e(y,e,t,r,n,void 0,void 0,i)}throw f}else if(n==="active"&&o.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await o.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await _e(m,e,t,r,n,void 0,void 0,i)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,h;switch(l){case "key":if(!o)f=!0,m="No adapter provided";else {let O;switch(n){case "owner":o.getOwnerKey&&(O=await o.getOwnerKey(e));break;case "active":o.getActiveKey&&(O=await o.getActiveKey(e));break;case "memo":o.getMemoKey&&(O=await o.getMemoKey(e));break;default:O=await o.getPostingKey(e);break}O?y=O:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":o?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!o)f=!0,m="No adapter provided";else {let O=await o.getAccessToken(e);O&&(h=O);}break;case "keychain":o?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await _e(l,e,t,r,n,y,h,i)}catch(f){if(a.set(l,f),!he(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},i,o="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async u=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(u);try{if(i?.enableFallback!==!1&&i?.adapter)return await Is(t,p,i,o,a);if(i?.broadcast)return await i.broadcast(p,o);let l=i?.postingKey;if(l){if(o!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${o}' was requested. Use AuthContextV2 with an adapter for ${o} operations.`);let m=H.fromString(l);return await Z(p,m)}let f=i?.accessToken;if(f)return (await new Gn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof X?new Error(l.message):l}}})}async function zn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let i={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",i]],"posting");let o=n?.postingKey;if(o){let u=H.fromString(o);return Z([["custom_json",i]],u)}let s=n?.accessToken;if(s)return (await new Gn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let u=[["custom_json",i]];if(n?.loginType==="keychain"&&a.broadcastWithKeychain)return a.broadcastWithKeychain(e,u,"posting");if(n?.loginType==="hiveauth"&&a.broadcastWithHiveAuth)return a.broadcastWithHiveAuth(e,u,"posting")}throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Mm=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function we(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,i=()=>{let o=t.aborted?t.reason:r.reason;n.abort(o),t.removeEventListener("abort",i),r.removeEventListener("abort",i);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true})),n.signal}var Fe=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),Bs=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},be=1e4,Jn=120*1e3,Ct,Ns;function Ms(){return Ct?Ct():Ns??=new QueryClient}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return E.nodes},heliusApiKey:Bs(),get queryClient(){return Ms()},set queryClient(e){Ct=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},M;(A=>{function e(P){d.queryClient=P;}A.setQueryClient=e;function t(P){Ct=P;}A.setQueryClientResolver=t;function r(P){d.privateApiHost=P;}A.setPrivateApiHost=r;function n(P){d.clientId=P;}A.setClientId=n;function i(P){if(typeof P!="string"||P.trim()==="")throw new Error("setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; observer resolution would fall back to the post author while caching under an empty key.");d.defaultObserver=P;}A.setDefaultObserver=i;function o(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}A.getValidatedBaseUrl=o;function s(P){d.pollsApiHost=P;}A.setPollsApiHost=s;function a(P){d.imageHost=P;}A.setImageHost=a;function u(P){Jt(P);}A.setHiveNodes=u;function p(P){Yt(P);}A.setRestNodes=p;function l(P){Xt(P);}A.setRestNodesByApi=l;function f(P){Zt(P);}A.setUserAgent=f;function m(P){er(P);}A.setResilience=m;function y(P){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(P))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(P))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(P))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(P)||/\.\+\.\+/.test(P))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let L=/\.?\{(\d+),(\d+)\}/g,U;for(;(U=L.exec(P))!==null;){let[,B,Q]=U;if(parseInt(Q,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${Q}}`}}return {safe:true}}function h(P){let L=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],U=5;for(let B of L){let Q=Date.now();try{P.test(B);let $=Date.now()-Q;if($>U)return {safe:!1,reason:`runtime test exceeded ${U}ms (took ${$}ms on input length ${B.length})`}}catch($){return {safe:false,reason:`runtime test threw error: ${$}`}}}return {safe:true}}function O(P,L=200){try{if(!P)return Fe&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(P.length>L)return Fe&&console.warn(`[SDK] DMCA pattern rejected: length ${P.length} exceeds max ${L} - pattern: ${P.substring(0,50)}...`),null;let U=y(P);if(!U.safe)return Fe&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${U.reason}) - pattern: ${P.substring(0,50)}...`),null;let B;try{B=new RegExp(P);}catch($){return Fe&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${P.substring(0,50)}...`,$),null}let Q=h(B);return Q.safe?B:(Fe&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Q.reason}) - pattern: ${P.substring(0,50)}...`),null)}catch(U){return Fe&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${P.substring(0,50)}...`,U),null}}function x(P={}){let L=$=>Array.isArray($)?$.filter(ke=>typeof ke=="string"):[],U=P||{},B={accounts:L(U.accounts),tags:L(U.tags),patterns:L(U.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map($=>O($)).filter($=>$!==null),d.dmcaPatternRegexes=[];let Q=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Fe&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${Q} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),Q>0&&console.warn(`[SDK] ${Q} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}A.setDmcaLists=x;})(M||={});function Ym(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,Vs;(s=>{function e(a){return b().getQueryData(a)}s.getQueryData=e;function t(a){return b().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await b().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await b().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function i(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=i;function o(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=o;})(Vs||={});function Zm(e){return btoa(JSON.stringify(e))}function eg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Yn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Yn||{}),Tt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Tt||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Yn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Tt[e.nai]}}var dr;function _(){if(!dr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");dr=globalThis.fetch.bind(globalThis);}return dr}function Xn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function js(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return js(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ve(e,t){return e/1e6*t}function Zn(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var ei=60*1e3;function ve(){return queryOptions({queryKey:c.core.dynamicProps(),refetchInterval:ei,staleTime:ei,queryFn:async({signal:e})=>{let[t,r,n,i,o]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=C(t.total_vesting_shares).amount,a=C(t.total_vesting_fund_hive).amount,u=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(u=a/s*1e6);let p=C(r.current_median_history.base).amount,l=C(r.current_median_history.quote).amount,f=parseFloat(i.recent_claims),m=C(i.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),h=i.author_reward_curve??"linear",O=Number(i.content_constant??0),x=String(o.current_hardfork_version??"0.0.0"),A=Number(o.last_hardfork??0),P=t.hbd_print_rate,L=t.hbd_interest_rate,U=t.head_block_number,B=a,Q=s,$=C(t.virtual_supply).amount,ke=t.vesting_reward_percent||0,Ze=n.account_creation_fee;return {hivePerMVests:u,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:h,contentConstant:O,currentHardforkVersion:x,lastHardfork:A,hbdPrintRate:P,hbdInterestRate:L,headBlock:U,totalVestingFund:B,totalVestingShares:Q,virtualSupply:$,vestingRewardPercent:ke,accountCreationFee:Ze,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:i,hardforkProps:o}}}})}function yg(e="post"){return queryOptions({queryKey:c.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function qe(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var c={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,i,o)=>["posts","account-posts-page",e,t,r,n,i,o],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>qe("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>qe("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>qe("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>qe("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,i,o)=>["posts","posts-ranked-page",e,t,r,n,i,o],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>qe("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>qe("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],subscribersInfinite:e=>["communities","subscribers","infinite",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,i,o)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,i,o],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,i,o)=>qe("search","api",e,t,r,n,i,o)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,i)=>["witnesses","voters",e,t,r,n,i],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"],resourceParams:()=>["resource-credits","resource-params"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],transcribePrice:e=>["ai","transcribe-price",e],_prefix:["ai"]}};function fr(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=0;for(let r=0;r=55296&&n<=56319&&r+1>>=7;while(r>0);return t}function Ag(e){return queryOptions({queryKey:c.ai.prices(),queryFn:async()=>{let r=await _()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function Eg(e,t){return queryOptions({queryKey:c.ai.assistPrices(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function Tg(e,t){return queryOptions({queryKey:c.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(d.privateApiHost+"/private-api/ai-transcribe-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI transcribe price: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function Ys(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ig(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??Ys()})});if(!i.ok){let s=await i.text(),a={};try{a=JSON.parse(s);}catch{}let u=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${i.status}${s?`: ${s}`:""}`);throw u.status=i.status,u.data=a,u}if(i.status===202){let s={};try{s=await i.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await i.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:c.points._prefix(e)});}})}function Zs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ng(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let i=await _()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Zs()})});if(!i.ok){let o=await i.text(),s={};try{s=JSON.parse(o);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${i.status}${o?`: ${o}`:""}`);throw a.status=i.status,a.data=s,a}return await i.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.assistPrices(e)}));}})}function ta(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;tt.toString(16).padStart(2,"0")).join("")}function Ug(e,t){return useMutation({mutationKey:["ai","transcribe"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Transcribe] \u2013 username wasn't provided");let n=r.code??t;if(!n)throw new Error("[SDK][AI][Transcribe] \u2013 access token wasn't found");let i=new FormData;i.append("code",n),i.append("duration_ms",String(Math.round(r.durationMs))),i.append("idempotency_key",r.idempotency_key??ta()),i.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:i});if(!s.ok){let a=await s.text(),u={};try{u=JSON.parse(a);}catch{}throw Object.assign(new Error(`[SDK][AI][Transcribe] \u2013 failed with status ${s.status}${a?`: ${a}`:""}`),{status:s.status,data:u})}return await s.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:c.points._prefix(e)}),b().invalidateQueries({queryKey:c.ai.transcribePrice(e)}));}})}function mr(e){return !e.posting_json_metadata&&!e.json_metadata}function na(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function N(e){return queryOptions({queryKey:c.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let i=r[0];if(mr(i)&&na(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!mr(l[0])));if(p[0]&&!mr(p[0]))i=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let o=Ie(i.posting_json_metadata),s=n?.stats,a=s?{account:i.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,u=n?.reputation??0;return {name:i.name,owner:i.owner,active:i.active,posting:i.posting,memo_key:i.memo_key,post_count:i.post_count,created:i.created,posting_json_metadata:i.posting_json_metadata,last_vote_time:i.last_vote_time,last_post:i.last_post,json_metadata:i.json_metadata,reward_hive_balance:i.reward_hive_balance,reward_hbd_balance:i.reward_hbd_balance,reward_vesting_hive:i.reward_vesting_hive,reward_vesting_balance:i.reward_vesting_balance,balance:i.balance,hbd_balance:i.hbd_balance,savings_balance:i.savings_balance,savings_hbd_balance:i.savings_hbd_balance,savings_hbd_last_interest_payment:i.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:i.savings_hbd_seconds_last_update,savings_hbd_seconds:i.savings_hbd_seconds,next_vesting_withdrawal:i.next_vesting_withdrawal,pending_claimed_accounts:i.pending_claimed_accounts,vesting_shares:i.vesting_shares,delegated_vesting_shares:i.delegated_vesting_shares,received_vesting_shares:i.received_vesting_shares,vesting_withdraw_rate:i.vesting_withdraw_rate,to_withdraw:i.to_withdraw,withdrawn:i.withdrawn,witness_votes:i.witness_votes,proxy:i.proxy,recovery_account:i.recovery_account,proxied_vsf_votes:i.proxied_vsf_votes,voting_manabar:i.voting_manabar,voting_power:i.voting_power,downvote_manabar:i.downvote_manabar,follow_stats:a,reputation:u,profile:o}},enabled:!!e,staleTime:6e4})}var ia=new Set(["__proto__","constructor","prototype"]);function Rt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ti(e,t){let r={...e};for(let n of Object.keys(t)){if(ia.has(n))continue;let i=t[n],o=r[n];Rt(i)&&Rt(o)?r[n]=ti(o,i):r[n]=i;}return r}function oa(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:i,...o}=t;return {...r,meta:o}})}function Ie(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function ri(e){return Ie(e?.posting_json_metadata)}function ni(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ie(e.posting_json_metadata)).length;return Object.keys(Ie(t.posting_json_metadata)).length>r?t:e}function sa(e){if(!e)return {};try{let t=JSON.parse(e);if(Rt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ii({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=sa(e),i=Rt(n.profile)?n.profile:{},o=gr({existingProfile:i,profile:t,tokens:r});return JSON.stringify({...n,profile:o})}function gr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:i,...o}=t??{},s=ti(e??{},o);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=oa(s.tokens),s.version=2,s}function Ft(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Ie(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let i=JSON.parse(t.json_metadata||"{}");i.profile&&(n=i.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function aa(e){return new TextEncoder().encode(e).length}function Le(e){return e?aa(e)<=16:false}function iy(e){return queryOptions({queryKey:c.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Le);if(t.length===0)return [];let r=await g("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ft(r??[])}})}function uy(e){return queryOptions({queryKey:c.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function my(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function wy(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var oi=1e3,fa=20;function Oy(e){return queryOptions({queryKey:c.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(o[0]===r&&(o=o.slice(1)),!o.length||(t.push(...o),i.lengthLe(e)?g("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Dy(e,t=5,r=[]){return queryOptions({queryKey:c.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(i=>r.length>0?!r.includes(i):true)})}var ha=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function My(e,t){return queryOptions({queryKey:c.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let i=await n.json(),o=Array.isArray(i)?i.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,u=typeof a.token=="string"?a.token:void 0;if(!u)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let h={symbol:u,currency:u,address:f,show:y,type:"CHAIN",meta:l},O=[];for(let[x,A]of Object.entries(p))typeof x=="string"&&(ha.has(x)||typeof A!="string"||!A||/^[A-Z0-9]{2,10}$/.test(x)&&O.push({symbol:x,currency:x,address:A,show:y,type:"CHAIN",meta:{address:A,show:y}}));return [h,...O]}):[];return {exist:o.length>0,tokens:o.length?o:void 0,wallets:o.length?o:void 0}},refetchOnMount:true})}function si(e,t){return queryOptions({queryKey:c.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>{let r={follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false};return !e||!t?r:await g("bridge.get_relationship_between_accounts",[e,t])??r}})}function Gy(e){return queryOptions({queryKey:c.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Xy(e,t){return queryOptions({queryKey:c.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Zy(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch bookmarks: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function nh(e,t){return queryOptions({queryKey:c.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function ih(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch favorites: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ch(e,t,r){return queryOptions({queryKey:c.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let i=await _()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!i.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${i.status}: ${i.statusText}`);let o=await i.json();if(typeof o!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof o}`);return o}})}function dh(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:c.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await _()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function hh(e){return queryOptions({enabled:!!e,queryKey:c.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function Ph(e,t=50){return queryOptions({queryKey:c.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Le(e)?[]:g("condenser_api.get_account_reputations",[e,t])})}var D=re.operations,ai={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.fill_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay]},Ca=Array.from(new Set(Object.values(ai).flat()));function Ta(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ra(e){return e.replace(/_operation$/,"")}function Fa(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function qa(e){if(!Fa(e))return e;let t=C(e),r=Tt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Ia(e){let t={};for(let[r,n]of Object.entries(e))t[r]=qa(n);return t}function Rh(e,t=20,r=""){let n=r?ai[r]:Ca;return infiniteQueryOptions({queryKey:c.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:i,signal:o})=>{if(!e)return {entries:[],currentPage:0};let s=async f=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return f!==null&&(m.page=f),await ee("hafah","/accounts/{account-name}/operations",m,void 0,void 0,o)},a=f=>f.operations_result.map(m=>{let y=Ra(m.op.type);return {...Ia(m.op.value),num:Ta(m),type:y,timestamp:m.timestamp,trx_id:m.trx_id}}),u=await s(i),p=a(u),l=i??u.total_pages;if(i===null&&p.length1)try{let f=await s(u.total_pages-1);p=[...p,...a(f)],l=u.total_pages-1;}catch(f){if(o?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:i=>{let o=i.currentPage-1;return o>=1?o:void 0}})}function Dh(){return queryOptions({queryKey:c.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function Mh(e){return infiniteQueryOptions({queryKey:c.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=M.getValidatedBaseUrl(),i=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&i.searchParams.set("max_id",r.toString());let o=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch referrals: ${o.status}`);return o.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Vh(e){return queryOptions({queryKey:c.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function zh(e,t,r){let{followType:n="blog",limit:i=100,enabled:o=true}=r??{};return infiniteQueryOptions({queryKey:c.accounts.friends(e,t,n,i),initialPageParam:{startFollowing:""},enabled:o,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,i])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===i?{startFollowing:s[s.length-1].name}:void 0})}var Qa=30;function e_(e,t,r){return queryOptions({queryKey:c.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(u=>t==="following"?u.following:u.follower).filter(u=>u.toLowerCase().includes(r.toLowerCase())).slice(0,Qa);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(u=>({name:u.name,full_name:u.metadata.profile?.name||"",reputation:u.reputation,active:u.active}))??[]}})}function o_(e=20){return infiniteQueryOptions({queryKey:c.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function l_(e=250){return infiniteQueryOptions({queryKey:c.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Xn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function $e(e,t){return queryOptions({queryKey:c.posts.fragments(e),queryFn:async()=>t?(await _()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function g_(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch fragments: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function w_(e="feed"){return queryOptions({queryKey:c.posts.promoted(e),queryFn:async()=>{let t=M.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await _()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function O_(e){return queryOptions({queryKey:c.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function C_(e,t,r){return queryOptions({queryKey:c.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function I_(e,t){return queryOptions({queryKey:c.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function M_(e,t){return queryOptions({queryKey:c.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function j_(e,t){return queryOptions({queryKey:c.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function te(e){return Array.isArray(e)?e.map(t=>ci(t)):ci(e)}function ci(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function ui(e,t,r){try{let n=await Et("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function pi(e,t,r="",n){let i=t?.trim(),o=`/@${e}/${i??""}`;return queryOptions({queryKey:c.posts.entry(o),queryFn:async()=>{if(!i||i==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:i,observer:r});if(!s){let u=await ui(e,i,r);if(!u)return null;let p=n!==void 0?{...u,num:n}:u;return te(p)}let a=n!==void 0?{...s,num:n}:s;return te(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function se(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function li(e,t,r,n){let{json_metadata:i}=e;if(i?.original_author&&i?.original_permlink&&i.tags?.[0]==="cross-post")try{let o=await Xa(i.original_author,i.original_permlink,t,r,n);return o?{...e,original_entry:o,num:r}:e}catch{return e}return {...e,num:r}}async function di(e,t,r){let n=e.map(st),i=await Promise.all(n.map(o=>li(o,t,void 0,r)));return te(i)}async function fi(e,t="",r="",n=20,i="",o="",s){let a=await se("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_ranked_posts returned ${typeof a} instead of an array for sort=${e}; treating as no results.`),null)}async function yr(e,t,r="",n="",i=20,o="",s){if(d.dmcaAccounts.includes(t))return [];let a=await se("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:i,observer:o},s);return Array.isArray(a)?di(a,o,s):(a!=null&&console.warn(`[SDK] get_account_posts returned ${typeof a} instead of an array for account=${t}, sort=${e}; treating as no results.`),null)}function st(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Xa(e="",t="",r="",n,i){let o=await se("get_post",{author:e,permlink:t,observer:r},i);if(o){let s=st(o),a=await li(s,r,n,i);return te(a)}}async function ow(e="",t=""){let r=await se("get_post_header",{author:e,permlink:t});return r&&st(r)}async function mi(e,t,r){let n=await se("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let i={};for(let[o,s]of Object.entries(n))i[o]=st(s);return i}return n}async function gi(e,t=""){return se("get_community",{name:e,observer:t})}async function sw(e="",t=100,r,n="rank",i=""){return se("list_communities",{last:e,limit:t,query:r,sort:n,observer:i})}async function yi(e){let t=await se("normalize_post",{post:e});return t&&st(t)}async function aw(e){return se("list_all_subscriptions",{account:e})}async function cw(e){return se("list_subscribers",{community:e})}async function uw(e,t){return se("get_relationship_between_accounts",[e,t])}async function qt(e,t){return se("get_profiles",{accounts:e,observer:t})}var _i=(i=>(i.trending="trending",i.author_reputation="author_reputation",i.votes="votes",i.created="created",i))(_i||{});function hr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Za(e,t,r){let n=l=>hr(l.pending_payout_value).amount+hr(l.author_payout_value).amount+hr(l.curator_payout_value).amount,i=l=>l.net_rshares<0,o=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(i(l))return 1;if(i(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m{let m=l.children,y=f.children;return m>y?-1:m{if(i(l))return 1;if(i(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:mo(l)),p=a[u];return u>=0&&(a.splice(u,1),a.unshift(p)),a}function wi(e,t="created",r=true,n){let i=n||d.defaultObserver;return queryOptions({queryKey:c.posts.discussions(e?.author,e?.permlink,t,i),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:i}),s=o?Array.from(Object.values(o)):[];return te(s)},enabled:r&&!!e,select:o=>Za(e,o,t),structuralSharing:(o,s)=>{if(!o||!s)return s;let a=o.filter(l=>l.is_optimistic===true),u=new Set(s.map(l=>`${l.author}/${l.permlink}`)),p=a.filter(l=>!u.has(`${l.author}/${l.permlink}`));return p.length>0?[...s,...p]:s}})}function yw(e,t,r,n=true){let i=r||d.defaultObserver;return queryOptions({queryKey:c.posts.discussion(e,t,i),enabled:n&&!!e&&!!t,queryFn:async()=>mi(e,t,i)})}function Pw(e,t="posts",r=20,n="",i=true){return infiniteQueryOptions({queryKey:c.posts.accountPosts(e??"",t,r,n),enabled:!!e&&i,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:o,signal:s})=>{if(!o?.hasNextPage||!e)return [];let a=await yr(t,e,o.author??"",o.permlink??"",r,n,s);return te(a??[])},getNextPageParam:o=>{let s=o?.[o.length-1],a=(o?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Ow(e,t="posts",r="",n="",i=20,o="",s=true){return queryOptions({queryKey:c.posts.accountPostsPage(e??"",t,r,n,i,o),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let u=await yr(t,e,r,n,i,o,a);return te(u??[])}})}var bi=new Map;function ic(e){let t=bi.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>oc(n,e))}),bi.set(e,t)),t}function oc(e,t){let r=e.filter(o=>o.stats?.is_pinned),n=e.filter(o=>!o.stats?.is_pinned);if(t==="hot")return [...r,...n];let i=[...n].sort((o,s)=>new Date(s.created).getTime()-new Date(o.created).getTime());return [...r,...i]}function Fw(e,t,r=20,n="",i=true,o={}){return infiniteQueryOptions({queryKey:c.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let u=t;d.dmcaTagRegexes.some(l=>l.test(t))&&(u="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:u,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);return te(p)},select:ic(e),enabled:i,initialPageParam:{author:void 0,permlink:void 0},getNextPageParam:s=>{let a=s?.[s.length-1];if(a)return {author:a.author,permlink:a.permlink}}})}function qw(e,t="",r="",n=20,i="",o="",s=true){return queryOptions({queryKey:c.posts.postsRankedPage(e,t,r,n,i,o),enabled:s,queryFn:async({signal:a}={})=>{let u=i;d.dmcaTagRegexes.some(l=>l.test(i))&&(u="");let p=await fi(e,t,r,n,u,o,a);return te(p??[])}})}function Nw(e,t,r=200){return queryOptions({queryKey:c.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(i=>i.author!==t&&!i.reblogged_on.startsWith("1970-")).map(i=>({author:i.author,permlink:i.permlink})),enabled:!!e})}function Vw(e,t){return queryOptions({queryKey:c.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Ww(e,t){return queryOptions({queryKey:c.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Gw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch schedules: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Xw(e,t){return queryOptions({queryKey:c.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Zw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch drafts: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Ai(e){let r=await _()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function nb(e,t){return queryOptions({queryKey:c.posts.images(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function ib(e,t){return queryOptions({queryKey:c.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Ai(t),enabled:!!e&&!!t})}function ob(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let o=await _()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!o.ok)throw new Error(`Failed to fetch images: ${o.status}`);let s=await o.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ub(e,t,r=false){return queryOptions({queryKey:c.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let i=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!i.ok)throw new Error(`Failed to fetch comment history: ${i.status}`);return i.json()},enabled:!!e&&!!t})}function gc(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let i=r.replace(/^@+/,""),o=n.replace(/^\/+/,"");if(!i||!o)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${i}/${o}`}function fb(e,t){let r=t?.trim(),n=e?.trim(),i=!!n&&!!r&&r!=="undefined",o=i?gc(n,r):"";return queryOptions({queryKey:c.posts.deletedEntry(o),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:u,tags:p}=s.list[0];return {body:a,title:u,tags:p}},enabled:i})}function hb(e,t,r=true){return queryOptions({queryKey:c.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch post tips: ${i.status}`);return i.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function hc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function _c(e){return {...e,id:e.id??e.post_id}}function me(e,t){if(!e)return null;let r=e.container??e,n=hc(r,t),i=e.parent?_c(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:i}}function wc(e){return Array.isArray(e)?e:[]}async function Pi(e){let t=wi(e,"created",true),r=await d.queryClient.fetchQuery(t),n=wc(r);if(n.length<=1)return [];let i=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return i.length===0?[]:i.filter(s=>!s.stats?.gray)}function Oi(e,t,r){return e.length===0?[]:e.map(n=>{let i=e.find(o=>o.author===n.parent_author&&o.permlink===n.parent_permlink&&o.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:i}}).filter(n=>n.container.post_id!==n.post_id).sort((n,i)=>new Date(i.created).getTime()-new Date(n.created).getTime())}var Ac=20;function xi(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Ac}}async function Ei({containers:e,tag:t,following:r,author:n,observer:i,limit:o},s,a){let u=M.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",u);p.searchParams.set("limit",String(o)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),i&&p.searchParams.set("observer",i);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=me(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function xb(e={}){let t=xi(e),{containers:r,tag:n,following:i,author:o,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:c.posts.wavesFeed({containers:r,tag:n,following:i,author:o,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:u,signal:p})=>Ei(t,u,p),getNextPageParam:u=>{if(!(u.lengthEi(t,void 0,u)})}var Oc=20;function xc(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??Oc}}async function Ec({containers:e,tag:t,author:r,observer:n,limit:i},o,s){let a=M.getValidatedBaseUrl(),u=new URL("/private-api/waves/shorts",a);u.searchParams.set("limit",String(i)),o&&u.searchParams.set("cursor",o),e.forEach(f=>u.searchParams.append("container",f)),t&&u.searchParams.set("tag",t),r&&u.searchParams.set("author",r),n&&u.searchParams.set("observer",n);let p=await fetch(u.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=me(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Rb(e={}){let t=xc(e),{containers:r,tag:n,author:i,observer:o,limit:s}=t;return infiniteQueryOptions({queryKey:c.posts.shortsFeed({containers:r,tag:n,author:i,observer:o,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:u})=>Ec(t,a,u),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of u){if(o&&l.post_id===o){o=void 0;continue}if(i+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Pi(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:Oi(f,l,e)}}let p=u[u.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Nb(e){return infiniteQueryOptions({queryKey:c.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await Tc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Fc=40;function Vb(e,t,r=Fc){return infiniteQueryOptions({queryKey:c.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/tags",i);o.searchParams.set("container",e),o.searchParams.set("tag",t);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>me(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves by tag",i),[]}},getNextPageParam:()=>{}})}function Gb(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/following",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>me(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){return console.error("[SDK] Failed to fetch waves following feed",i),[]}},getNextPageParam:()=>{}})}function Xb(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:c.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/trending/tags",i);r&&o.searchParams.set("container",r),o.searchParams.set("hours",t.toString());let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:u,posts:p})=>({tag:u,posts:p}))}catch(i){return console.error("[SDK] Failed to fetch waves trending tags",i),[]}}})}function nv(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let i=M.getValidatedBaseUrl(),o=new URL("/private-api/waves/account",i);o.searchParams.set("container",e),o.searchParams.set("username",r);let s=await fetch(o.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>me(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(i){throw console.error("[SDK] Failed to fetch waves for account",i),i}},getNextPageParam:()=>{}})}function av(e){return queryOptions({queryKey:c.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=M.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let i=await fetch(n.toString(),{method:"GET",signal:t});if(!i.ok)throw new Error(`Failed to fetch waves trending authors: ${i.status}`);return (await i.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function dv(e,t=true){return queryOptions({queryKey:c.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>yi(e)})}function Mc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Si(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function bv(e,t){let{limit:r=20,filters:n=[],dayLimit:i=7}=t??{};return infiniteQueryOptions({queryKey:c.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:o})=>{let{start:s}=o,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Si(m.timestamp)<=i),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(pi(m.author,m.permlink));Mc(y)&&l.push(y);}let[f]=a;return {lastDate:f?Si(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:o=>({start:o.lastItemFetched})})}function xv(e,t,r=true){return queryOptions({queryKey:c.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>qt(e,t)})}function Rv(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:c.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:i})=>{if(!e)return {entries:[],currentPage:0};let o={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(o.page=n);let s=await ee("balance","/accounts/{account-name}/balance-history",o,void 0,void 0,i);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let i=n.currentPage-1;return i>=1?i:void 0},enabled:!!e})}function Kv(e,t="HIVE",r="yearly"){return queryOptions({queryKey:c.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ee("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function Qv(){return queryOptions({queryKey:c.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function Hv(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Wv(e,t,r){let n=useQueryClient(),{data:i}=useQuery(N(e));return v(["accounts","update"],e,o=>{let s=ni(n.getQueryData(N(e).queryKey),i);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ii({existingPostingJsonMetadata:s.posting_json_metadata,profile:o.profile,tokens:o.tokens})}]]},async(o,s)=>{n.setQueryData(N(e).queryKey,a=>{if(!a)return a;let u=JSON.parse(JSON.stringify(a));return u.profile=gr({existingProfile:ri(a),profile:s.profile,tokens:s.tokens}),u}),await S(t?.adapter,r,[c.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...N(e),staleTime:0});}catch{}}})}function Xv(e,t,r,n,i){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async o=>{let s=si(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await zn(e,"follow",["follow",{follower:e,following:t,what:[...o==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...o==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:o==="toggle-ignore"?!a?.ignores:a?.ignores,follows:o==="toggle-follow"?!a?.follows:a?.follows}},onError:i,onSuccess(o){n(o),b().setQueryData(c.accounts.relations(e,t),o),t&&b().invalidateQueries(N(t));}})}function _r(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function De(e,t,r,n,i,o,s){if(!e||!t||n===void 0||!o)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:i,body:o,json_metadata:JSON.stringify(s)}]}function Ke(e,t,r,n,i,o,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:i,allow_curation_rewards:o,extensions:s}]}function wr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function br(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let i={account:e,author:t,permlink:r};return n&&(i.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",i]),required_auths:[],required_posting_auths:[e]}]}function Be(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function Wc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(o=>Be(e,o.trim(),r,n))}function Gc(e,t,r,n,i,o){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(i<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:i,executions:o,extensions:[]}]}function We(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function Ne(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:i}]}function ki(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function at(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ne(e,t,r,n,i),ki(e,i)]}function ct(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function ut(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function pt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function lt(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function dt(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function vr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Me(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function Ar(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Pr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(i=>i.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function Or(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function It(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function zc(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function Jc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return It(e,t)}function xr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],i=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,i]}function Er(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function Sr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function kr(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function Cr(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function Yc(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function Xc(e,t,r,n,i){if(e==null||typeof e!="number"||!t||!r||!n||!i)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:i,extensions:[]}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Rr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Fr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function qr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Ir(e,t,r,n,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Dr(e,t,r,n,i,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}function Zc(e,t,r,n,i){if(!e||!t||!r||i===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function eu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:i}]),required_auths:[],required_posting_auths:[e]}]}var Ci=(r=>(r.Buy="buy",r.Sell="sell",r))(Ci||{}),Ti=(r=>(r.EMPTY="",r.SWAP="9",r))(Ti||{});function Kt(e,t,r,n,i,o){if(!e||!t||!r||!i||o===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:o,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:i}]}function Dt(e,t=3){return e.toFixed(t)}function tu(e,t,r,n,i=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let o=new Date(Date.now());o.setDate(o.getDate()+27);let s=o.toISOString().split(".")[0],a=+`${i}${Math.floor(Date.now()/1e3).toString().slice(2)}`,u=n==="buy"?`${Dt(t,3)} HBD`:`${Dt(t,3)} HIVE`,p=n==="buy"?`${Dt(r,3)} HIVE`:`${Dt(r,3)} HBD`;return Kt(e,u,p,false,s,a)}function Kr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Br(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function ru(e,t,r,n,i,o){if(!e||!i)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:i,json_metadata:o}]}function nu(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function Nr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let i={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:i,active:o,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Mr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},o={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:i,posting:o,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Qr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Hr(e,t,r,n,i,o){if(!e||!t||!r||!i)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let u={...t,account_auths:a};return u.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:u,memo_key:i,json_metadata:o}]}function iu(e,t,r,n,i){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let o={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:o,memo_key:n,json_metadata:i}]}function ou(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function su(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function au(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Ur(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function Vr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function jr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Ge(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let i=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:i,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function cu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let i=t.trim().split(/[\s,]+/).filter(Boolean);if(i.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return i.map(o=>Ge(e,o.trim(),r,n))}function Lr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function uu(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function pu(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function wA(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Or(e,n)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function PA(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[It(e,n)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.relations(e,i.following),c.accounts.full(i.following),c.accounts.followCount(i.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function SA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:i,permlink:o})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:i,permlink:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function RA(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function DA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})})).json()},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:n})}function QA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async i=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:i,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async i=>{if(!e)return;let o=b(),s=c.accounts.favorites(e),a=c.accounts.favoritesInfinite(e),u=c.accounts.checkFavorite(e,i);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a}),o.cancelQueries({queryKey:u})]);let p=o.getQueryData(s);p&&o.setQueryData(s,p.filter(y=>y.account!==i));let l=o.getQueryData(u);o.setQueryData(u,false);let f=o.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,h]of f)h&&o.setQueryData(y,{...h,pages:h.pages.map(O=>({...O,data:O.data.filter(x=>x.account!==i)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(i,o)=>{r();let s=b();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,o)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);s?.previousCheck!==void 0&&a.setQueryData(c.accounts.checkFavorite(e,o),s.previousCheck),n(i);}})}function hu(e,t){let r=new Map;return e.forEach(([n,i])=>{r.set(n.toString(),i);}),t.forEach(([n,i])=>{r.set(n.toString(),i);}),Array.from(r.entries()).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,i])}function Ri(e,t){let{data:r}=useQuery(N(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:i=false,currentKey:o,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let u=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=i?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=hu(y,n.map((h,O)=>[h[p].createPublic().toString(),O+1])),l};return Z([["account_update",{account:e,json_metadata:r.json_metadata,owner:u("owner"),active:u("active"),posting:u("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],o)},...t})}function JA(e,t){let{data:r}=useQuery(N(e)),{mutateAsync:n}=Ri(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:i,currentPassword:o,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,o,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,i,"owner"),active:H.fromLogin(e,i,"active"),posting:H.fromLogin(e,i,"posting"),memo_key:H.fromLogin(e,i,"memo")}]})},...t})}function rP(e,t,r){let n=useQueryClient(),{data:i}=useQuery(N(e));return useMutation({mutationKey:["accounts","revoke-posting",i?.name],mutationFn:async({accountName:o,type:s,key:a})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let u=JSON.parse(JSON.stringify(i.posting));u.account_auths=u.account_auths.filter(([l])=>l!==o);let p={account:i.name,posting:u,memo_key:i.memo_key,json_metadata:i.json_metadata};if(s==="key"&&a)return Z([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(i.name,[["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),Gn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(o,s,a)=>{t.onSuccess?.(o,s,a),n.setQueryData(N(e).queryKey,u=>({...u,posting:{...u?.posting,account_auths:u?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function uP(e,t,r,n){let{data:i}=useQuery(N(e));return useMutation({mutationKey:["accounts","recovery",i?.name],mutationFn:async({accountName:o,type:s,key:a,email:u})=>{if(!i)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:i.name,new_recovery_account:o,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await _()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:u,publicKeys:[...i.owner.key_auths,...i.active.key_auths,...i.posting.key_auths,i.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Z([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.adapter.broadcastWithKeychain(i.name,[["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),Gn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function lP(e,t){let r=e.key_auths.filter(([i])=>!t.has(String(i))).reduce((i,[,o])=>i+o,0),n=(e.account_auths??[]).reduce((i,[,o])=>i+o,0);return r+n>=e.weight_threshold}function Fi(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),i=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([u])=>!r.has(u.toString())),a},o=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:o?i(e.owner):void 0,active:i(e.active),posting:i(e.posting),memo_key:e.memo_key}}function hP(e,t){let{data:r}=useQuery(N(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:i})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let o=Array.isArray(i)?i:[i],s=Fi(r,o);return Z([["account_update",s]],n)},...t})}function vP(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:i="0.000 HIVE"})=>[Qr(n,i)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(i.creator)]);},t,"active",{broadcastMode:r})}function xP(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Hr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await S(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}function CP(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Mr(e,n.newAccountName,n.keys):Nr(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}var $r=300*60*24,Cu=1e4,Tu=5e7;function qi(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,i=C(e.vesting_withdraw_rate).amount,o=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(i,o);return t+r-n-s}function Ru(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Fu(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function qu(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let i=qi(e);if(!Number.isFinite(i)||i<=0)return 0;let o=i*1e6,s=Math.ceil(o*r*60*60*24/Cu/(n*$r)),a=lr(e),u=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(u)||s>u?0:Math.max(s-Tu,0)}function Iu(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Fu(t))return qu(e,t,n);let i=0;try{if(i=qi(e),!Number.isFinite(i))return 0}catch{return 0}return Ru(i,r,n)}function qP(e){return lr(e).percentage/100}function IP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*$r/1e4}function DP(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let i=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/$r;i>n&&(i=n);let o=i*100/n;return isNaN(o)?0:o>100?100:o}function KP(e){return kt(e).percentage/100}function BP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:i,fundRewardBalance:o,base:s,quote:a}=t;if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(a)||i===0||a===0)return 0;let u=Iu(e,t,r,n);return Number.isFinite(u)?u/i*o*(s/a):0}var Du={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function Ku(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function Bu(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function Nu(e){let t=e[0];return t==="custom_json"?Ku(e):t==="create_proposal"||t==="update_proposal"?Bu(e):Du[t]??"posting"}function MP(e){let t="posting";for(let r of e){let n=Nu(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function jP(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):jn(r)?n=H.fromString(r):n=H.from(r),Z([t],n)}})}function WP(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.adapter.broadcastWithKeychain(e,[n],r)}})}function YP(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Gn.sendOperation(t,{callback:e},()=>{})})}function t0(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Ii(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Di(e,t){return {...e??{},title:t.title,body:t.body}}function u0(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await _()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${o.status}`);return o.json()},onSuccess(r,n){let i=b(),o=Di(r,n);i.setQueryData($e(e,t).queryKey,s=>[o,...s??[]]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,u)=>u===0?{...a,data:[o,...a.data]}:a)});}})}function y0(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:i})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:i}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let i=b(),o=s=>Ii(s,r,n);i.setQueryData($e(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?o(a):a)??[]),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(u=>u.id===n.fragmentId?o(u):u)}))});}})}function A0(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await _()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${i.status}`);return i},onSuccess(r,n){let i=b();i.setQueryData($e(e,t).queryKey,o=>[...o??[]].filter(({id:s})=>s!==n.fragmentId)),i.setQueriesData({queryKey:["posts","fragments","infinite",e]},o=>o&&{...o,pages:o.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function G(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function x0(e,t,r,n){let o=await _()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await G(o);return {status:o.status,data:s}}async function E0(e){let r=await _()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await G(r);return {status:r.status,data:n}}async function S0(e,t,r="",n=""){let i={code:e,ty:t};r&&(i.bl=r),n&&(i.tx=n);let s=await _()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});await G(s);}async function k0(e,t,r=null,n=null){let i={code:e};t&&(i.filter=t),r&&(i.since=r),n&&(i.user=n);let s=await _()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(s)}async function C0(e,t,r,n,i,o){let s={code:e,username:t,token:o,system:r,allows_notify:n,notify_types:i},u=await _()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(u)}async function T0(e,t,r){let n={code:e,username:t,token:r},o=await _()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function Ki(e,t){let r={code:e};t&&(r.id=t);let i=await _()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Bi(e,t){let r={code:e,url:t},i=await _()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}var Wu="https://i.ecency.com";async function Ni(e,t,r){let n=_(),i=new FormData;i.append("file",e);let o=await n(`${Wu}/hs/${t}`,{method:"POST",body:i,signal:r});return G(o)}async function R0(e,t,r,n){let i=_(),o=new FormData;o.append("file",e);let s=await i(`${d.imageHost}/${t}/${r}`,{method:"POST",body:o,signal:n});return G(s)}async function Mi(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Qi(e,t,r,n,i){let o={code:e,title:t,body:r,tags:n,meta:i},a=await _()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(a)}async function Hi(e,t,r,n,i,o){let s={code:e,id:t,title:r,body:n,tags:i,meta:o},u=await _()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(u)}async function Ui(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Vi(e,t,r,n,i,o,s,a){let u={code:e,permlink:t,title:r,body:n,meta:i,schedule:s,reblog:a};o&&(u.options=o);let l=await _()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return G(l)}async function ji(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function Li(e,t){let r={code:e,id:t},i=await _()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(i)}async function F0(e,t,r){let n={code:e,author:t,permlink:r},o=await _()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}async function q0(e,t,r){let n={username:e,email:t,friend:r},o=await _()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(o)}function N0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:i,body:o,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return Qi(t,i,o,s,a)},onSuccess:i=>{r?.();let o=b();i?.drafts?o.setQueryData(c.posts.drafts(e),i.drafts):o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function V0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:i,title:o,body:s,tags:a,meta:u})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Hi(t,i,o,s,a,u)},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function z0(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return Ui(t,i)},onMutate:async({draftId:i})=>{if(!e)return;let o=b(),s=c.posts.drafts(e),a=c.posts.draftsInfinite(e);await Promise.all([o.cancelQueries({queryKey:s}),o.cancelQueries({queryKey:a})]);let u=o.getQueryData(s);u&&o.setQueryData(s,u.filter(f=>f._id!==i));let p=o.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&o.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(h=>h._id!==i)}))});return {previousList:u,previousInfinite:l}},onSuccess:()=>{r?.();let i=b();i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:(i,o,s)=>{let a=b();if(s?.previousList&&a.setQueryData(c.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);n?.(i);}})}function eO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:i,title:o,body:s,meta:a,options:u,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Vi(t,i,o,s,a,u,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function oO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return ji(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function pO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return Li(t,i)},onSuccess:i=>{r?.();let o=b();i?o.setQueryData(c.posts.schedules(e),i):o.invalidateQueries({queryKey:c.posts.schedules(e)}),o.invalidateQueries({queryKey:c.posts.drafts(e)});},onError:n})}function gO(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:i,code:o})=>{let s=o??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Bi(s,i)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:c.posts.images(e)});},onError:n})}function bO(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:i})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return Mi(t,i)},onSuccess:(i,o)=>{r?.();let s=b(),{imageId:a}=o;s.setQueryData(["posts","images",e],u=>u?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},u=>u&&{...u,pages:u.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function OO(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:i})=>Ni(r,n,i),onSuccess:e,onError:t})}function Nt(e,t){return `/@${e}/${t}`}function np(e,t,r){return (r??b()).getQueryData(c.posts.entry(Nt(e,t)))}function ip(e,t){(t??b()).setQueryData(c.posts.entry(Nt(e.author,e.permlink)),e);}function Bt(e,t,r,n){let i=n??b(),o=Nt(e,t),s=i.getQueryData(c.posts.entry(o));if(!s)return;let a=r(s);return i.setQueryData(c.posts.entry(o),a),s}var Qe;(a=>{function e(u,p,l,f,m){Bt(u,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(u,p,l,f){Bt(u,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(u,p,l,f){Bt(u,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(u,p,l,f){Bt(p,l,m=>({...m,children:m.children+1,replies:[u,...m.replies]}),f);}a.addReply=n;function i(u,p){u.forEach(l=>ip(l,p));}a.updateEntries=i;function o(u,p,l){(l??b()).invalidateQueries({queryKey:c.posts.entry(Nt(u,p))});}a.invalidateEntry=o;function s(u,p,l){return np(u,p,l)}a.getEntry=s;})(Qe||={});function op(e,t,r){let n=e.some(i=>i.voter===t);return r!==0?n:!n}function sp(e,t,r){let n=Qe.getEntry(t.author,t.permlink,r);if(!n?.active_votes||op(n.active_votes,e,t.weight))return;let i=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],o=n.payout+(t.estimated??0);Qe.updateVotes(t.author,t.permlink,i,o,r);}function RO(e,t,r){return v(["posts","vote"],e,({author:n,permlink:i,weight:o})=>[_r(e,n,i,o)],async(n,i)=>{sp(e,i);let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(120,o,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function KO(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:i,deleteReblog:o})=>[br(e,n,i,o??false)],async(n,i)=>{let o=Qe.getEntry(i.author,i.permlink);if(o){let p=Math.max(0,(o.reblogs??0)+(i.deleteReblog?-1:1));Qe.updateReblogsCount(i.author,i.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{b().invalidateQueries({queryKey:c.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([c.posts.entry(`/@${i.author}/${i.permlink}`),c.posts.rebloggedBy(i.author,i.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function QO(e,t,r){return v(["posts","comment"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Ke(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=!i.parentAuthor,s=o?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let u=[c.accounts.full(e),c.resourceCredits.account(e)];if(!o){u.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let p=i.rootAuthor||i.parentAuthor,l=i.rootPermlink||i.parentPermlink;u.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(u);}},t,"posting",{broadcastMode:r})}function VO(e,t,r,n){let i=n??b(),o=i.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of o)a&&i.setQueryData(s,[e,...a]);}function $i(e,t,r,n,i){let o=i??b(),s=new Map,a=o.getQueriesData({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[u,p]of a)p&&(s.set(u,p),o.setQueryData(u,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Wi(e,t){let r=t??b();for(let[n,i]of e)r.setQueryData(n,i);}function jO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`,s=i.getQueryData(c.posts.entry(o));return s&&i.setQueryData(c.posts.entry(o),{...s,...r}),s}function LO(e,t,r,n){let i=n??b(),o=`/@${e}/${t}`;i.setQueryData(c.posts.entry(o),r);}function JO(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:i})=>[wr(n,i)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e)];if(i.parentAuthor&&i.parentPermlink){o.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let s=i.rootAuthor||i.parentAuthor,a=i.rootPermlink||i.parentPermlink;o.push({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let i=n.rootAuthor||n.parentAuthor,o=n.rootPermlink||n.parentPermlink;return i&&o?{snapshots:$i(n.author,n.permlink,i,o)}:{}},onError:(n,i,o)=>{let{snapshots:s}=o??{};s&&Wi(s);}})}function ex(e,t,r){return v(["posts","cross-post"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true}=n.options;i.push(Ke(n.author,n.permlink,o,s,a,u,[]));}return i},async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.parentPermlink}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"async"})}function ix(e,t,r){return v(["posts","update-reply"],e,n=>{let i=[];if(i.push(De(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:o="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}i.push(Ke(n.author,n.permlink,o,s,a,u,l));}return i},async(n,i)=>{let o=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(110,o,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:o,error:s});}),t?.adapter?.invalidateQueries){let s=[c.resourceCredits.account(e)];s.push(c.posts.entry(`/@${i.parentAuthor}/${i.parentPermlink}`));let a=i.rootAuthor||i.parentAuthor,u=i.rootPermlink||i.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===u}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function cx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:i,duration:o})=>[jr(e,n,i,o)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.posts._promotedPrefix],[...c.points._prefix(e)],c.posts.entry(`/@${i.author}/${i.permlink}`)]);},t,"active",{broadcastMode:r})}var ap=[3e3,3e3,3e3],cp=e=>new Promise(t=>setTimeout(t,e));async function up(e,t){return g("condenser_api.get_content",[e,t])}async function pp(e,t,r=0,n){let i=n?.delays??ap,o;try{o=await up(e,t);}catch{o=void 0;}if(o||r>=i.length)return;let s=i[r];return s>0&&await cp(s),pp(e,t,r+1,n)}var ze={};ht(ze,{useRecordActivity:()=>Wr});function dp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Wr(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=_(),i=dp(),o=r?.url??i.url,s=r?.domain??i.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:o,domain:s,props:{username:e}})});}catch{}}})}function _x(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function Px(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),i=n.map(s=>s.account),o=await g("condenser_api.get_accounts",[i]);for(let s=0;sa.efficiency-s.efficiency),n}})}function Sx(e,t=[],r=["visitors","pageviews","visit_duration"],n){let i=[...t].sort(),o=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,i,o,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Mt="threespeakfund",qx=1100;function yp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function Ix(e,t){if(!yp(t))return e;let r=e.find(n=>n.account===Mt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Mt?{...n,weight:1100}:n):[...e,{account:Mt,weight:1100}]}function Dx(e){return e===Mt}var Jr={};ht(Jr,{getAccountTokenQueryOptions:()=>zr,getAccountVideosQueryOptions:()=>Ap});var Gr={};ht(Gr,{getDecodeMemoQueryOptions:()=>wp});function wp(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Gn.Client({accessToken:r}).decode(t)}})}var Gi={queries:Gr};function zr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await _()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),i=Gi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(i);let{memoDecoded:o}=b().getQueryData(i.queryKey);return o.replace("#","")}})}function Ap(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=zr(e,t);await b().prefetchQuery(r);let n=b().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await _()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var Xx={queries:Jr};function iE(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await _()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function cE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:i,enabled:o=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,i],queryFn:async()=>{let a=await _()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...i?{date_range:i}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&o,retry:1})}function dE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function yE(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function vE(){return queryOptions({queryKey:c.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await g("rc_api.get_resource_params",{})})}var zi=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var Ji={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function xE({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Ji;let{current_mana:i,max_mana:o}=kt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Ji,ready:true,currentMana:i,maxMana:o};let a=Number.isFinite(n)&&n>0?n:1.2,u=s*a,p=iBigInt(typeof e=="string"?e:Math.trunc(e));function Rp(e,t,r,n){if(r<=0||n<=0)return 0;let i=Je(e.coeff_a),o=Je(e.coeff_b),s=Je(e.shift),a=Je(n)*i>>s;a+=1n,a*=Je(r);let u=o+(t>0?Je(t):0n);return u===0n?0:Number(a/u+1n)}function Fp({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:i=false},o){let s=o.resource_state_bytes,a=o.resource_execution_time;return {resource_history_bytes:e,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:s.comment_base_size+s.comment_permlink_char_size*t+s.transaction_base_size+s.comment_beneficiaries_member_size*n,resource_execution_time:a.comment_time+a.transaction_time+a.verify_authority_time*r+(i?a.comment_options_time:0)}}var ge=e=>{let t=fr(e);return je(t)+t},qp=e=>1+ge(e.parent_author)+ge(e.parent_permlink)+ge(e.author)+ge(e.permlink)+ge(e.title)+ge(e.body)+ge(e.json_metadata),Ip=(e,t)=>{let r=t.beneficiaries??[],n=1+ge(e.author)+ge(e.permlink)+Tp+2+2;return n+=je(r.length>0?1:0),r.length>0&&(n+=1+je(r.length),r.forEach(i=>{n+=ge(i.account)+2;})),n};function Dp({op:e,options:t,signatures:r=1}){let n=[qp(e)];return t&&n.push(Ip(e,t)),kp+je(n.length)+n.reduce((i,o)=>i+o,0)+je(r)+Cp*r}var Kp={ready:false,cost:0,transactionBytes:0,breakdown:[]};function CE({op:e,options:t,rcParams:r,rcStats:n,signatures:i=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return Kp;let o=Dp({op:e,options:t,signatures:i}),s=Fp({transactionBytes:o,permlinkLength:fr(e.permlink),signatures:i,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),u=0,p=[];return zi.forEach((l,f)=>{let m=r.resource_params[l],y=Number(n.pool[f]??0),h=Number(n.share[f]??0);if(!m||h<=0)return;let O=s[l]*Number(m.resource_dynamics_params.resource_unit??1),x=Number(BigInt(a)*BigInt(h)/10000n),A=Rp(m.price_curve_params,y,O,x);u+=A,p.push({resource:l,usage:O,cost:A});}),{ready:true,cost:u,transactionBytes:o,breakdown:p}}function qE(e,t,r){return queryOptions({queryKey:["games","status-check",r,e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function NE(e,t,r,n){let{mutateAsync:i}=Wr(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await _()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){i();}})}function UE(e){let t=e?.replace("@","");return queryOptions({queryKey:c.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await _()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var Qp=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function jE(e,t){return Qp.find(r=>r.tier===e&&r.id===t)}var Hp=25;function Up(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function LE(e){return Up(e)>Hp}var $E=300,WE=2;function Lp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function $p(e){let r=await _()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Lp()})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to buy streak freeze: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function YE(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return $p(t)},onSuccess(){n&&r.invalidateQueries({queryKey:c.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:c.quests.status(n)});}})}function tS(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Tr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"async"})}function oS(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Rr(e,n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(i.community)],c.communities.context(e,i.community)]);},t,"posting",{broadcastMode:r??"sync"})}function uS(e,t,r){return v(["communities","mutePost"],e,({community:n,author:i,permlink:o,notes:s,mute:a})=>[Dr(e,n,i,o,s,a)],async(n,i)=>{if(t?.adapter?.invalidateQueries){let o=[c.posts.entry(`/@${i.author}/${i.permlink}`),["community","single",i.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===i.community}}];await t.adapter.invalidateQueries(o);}},t,"posting",{broadcastMode:r??"sync"})}function fS(e,t,r,n){return v(["communities","set-role",e],t,({account:i,role:o})=>[Fr(t,e,i,o)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>{if(!a)return a;let u=[...a.team??[]],p=u.findIndex(([l])=>l===o.account);return p>=0?u[p]=[u[p][0],o.role,u[p][2]??""]:u.push([o.account,o.role,""]),{...a,team:u}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)],c.communities.context(o.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function hS(e,t,r,n){return v(["communities","update",e],t,i=>[qr(t,e,i)],async(i,o)=>{b().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>a&&{...a,...o}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function vS(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Lr(n)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.communities.singlePrefix(i.name)],[...c.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function xS(e,t,r){return v(["communities","pin-post"],e,({community:n,account:i,permlink:o,pin:s})=>[Ir(e,n,i,o,s)],async(n,i)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.posts.entry(`/@${i.account}/${i.permlink}`),[...c.communities.singlePrefix(i.community)]]);},t,"posting",{broadcastMode:r??"async"})}function TS(e,t,r=100,n=void 0,i=true){return queryOptions({queryKey:c.communities.list(e,t??"",r),enabled:i,queryFn:async()=>{let o=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return o?e==="hot"?o.sort(()=>Math.random()-.5):o:[]}})}function DS(e,t){return queryOptions({queryKey:c.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function QS(e,t="",r=true){return queryOptions({queryKey:c.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>gi(e??"",t)})}var Yi=100;async function Xi(e,t){return await g("bridge.list_subscribers",{community:e,limit:Yi,...t?{last:t}:{}})??[]}function $S(e){return queryOptions({queryKey:c.communities.subscribers(e),queryFn:async()=>Xi(e,null),staleTime:6e4})}function WS(e){return infiniteQueryOptions({queryKey:c.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Xi(e,t),getNextPageParam:t=>t?.length>=Yi?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function ZS(e,t){return infiniteQueryOptions({queryKey:c.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function nk(){return queryOptions({queryKey:c.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var el=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(el||{}),ok={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function ak(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function ck({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),i=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),o=["owner","admin","mod"].includes(t);return {canPost:n,canComment:i,isModerator:o}}function dk(e,t){return queryOptions({queryKey:c.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function yk(e,t,r=void 0){return infiniteQueryOptions({queryKey:c.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let i={code:t,filter:r,since:n,user:void 0},o=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return [];try{return await o.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var nl=(y=>(y.VOTES="rvotes",y.MENTIONS="mentions",y.FAVORITES="nfavorites",y.BOOKMARKS="nbookmarks",y.FOLLOWS="follows",y.REPLIES="replies",y.REBLOGS="reblogs",y.TRANSFERS="transfers",y.DELEGATIONS="delegations",y.PAYOUTS="payouts",y.SCHEDULED_PUBLISHED="scheduled_published",y.ACCOUNT_UPDATES="account_updates",y.WEEKLY_EARNINGS="weekly_earnings",y))(nl||{});var il=(h=>(h[h.VOTE=1]="VOTE",h[h.MENTION=2]="MENTION",h[h.FOLLOW=3]="FOLLOW",h[h.COMMENT=4]="COMMENT",h[h.RE_BLOG=5]="RE_BLOG",h[h.TRANSFERS=6]="TRANSFERS",h[h.DELEGATIONS=10]="DELEGATIONS",h[h.FAVORITES=13]="FAVORITES",h[h.BOOKMARKS=15]="BOOKMARKS",h[h.PAYOUTS=19]="PAYOUTS",h[h.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",h[h.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",h[h.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",h.ALLOW_NOTIFY="ALLOW_NOTIFY",h))(il||{}),Zi=[1,2,3,4,5,6,10,13,15,19,20,21,22],ol=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(ol||{});function Pk(e,t,r){return queryOptions({queryKey:c.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let i=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch notification settings: ${i.status}`);return i.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Zi]})})}function Sk(){return queryOptions({queryKey:c.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function Rk(e){return queryOptions({queryKey:c.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function pl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function eo(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function Nk(e,t,r,n){let i=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:o})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Ki(t,o)},onMutate:async({id:o})=>{if(!e||!t)return {previousData:[]};await i.cancelQueries({queryKey:c.notifications._prefix});let s=[],a=i.getQueriesData({queryKey:c.notifications._prefix,predicate:l=>{let f=l.state.data;return eo(f)}});a.forEach(([l,f])=>{if(f&&eo(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(h=>pl(h,o)))};i.setQueryData(l,m);}});let u=c.notifications.unreadCount(e),p=i.getQueryData(u);return typeof p=="number"&&p>0&&(s.push([u,p]),o?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===o&&y.read===0)))&&i.setQueryData(u,p-1):i.setQueryData(u,0)),{previousData:s}},onSuccess:o=>{let s=typeof o=="object"&&o!==null?o.unread:void 0;typeof s=="number"&&i.setQueryData(c.notifications.unreadCount(e),s),r?.(s);},onError:(o,s,a)=>{a?.previousData&&a.previousData.forEach(([u,p])=>{i.setQueryData(u,p);}),n?.(o);},onSettled:()=>{i.invalidateQueries({queryKey:c.notifications._prefix});}})}function Uk(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>xr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function $k(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)=new Date?r.status="active":new Date(r.end_date){let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(i=>i.status==="expired");return [...t.filter(i=>i.status!=="expired"),...r]}})}function rC(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),u=Ft(a);return s.map(l=>({...l,voterAccount:u.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function sC(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function pC(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:i})=>[Cr(e,n,i)],async n=>{try{let i=n?.id??n?.tx_id;t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(150,i,n?.block_num).catch(o=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:i,error:o});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.proposals.list(),c.proposals.votesByUser(e)]);}catch(i){console.warn("[useProposalVote] Post-broadcast side-effect failed:",i);}},t,"active",{broadcastMode:r})}function mC(e,t,r){return v(["proposals","create"],e,n=>[kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.proposals.list()]);},t,"active",{broadcastMode:r})}function _C(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,i=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&i.length>0&&i[0]?.delegatee===r?i.slice(1,t+1):i},getNextPageParam:r=>!r||r.lengthee("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function EC(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function TC(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function IC(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function NC(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function UC(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function $C(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function YC(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let i=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(o=>o)).rc_direct_delegations||[];return r&&(i=i.filter(o=>o.to!==r)),i},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function tT(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await _()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function oT(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function uT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function le(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let i=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(i){let o=Number.parseFloat(i[0]);if(Number.isFinite(o))return o}}}function kl(e){if(!e||typeof e!="object")return;let t=e;return {name:le(t.name)??"",symbol:le(t.symbol)??"",layer:le(t.layer)??"hive",balance:ae(t.balance)??0,fiatRate:ae(t.fiatRate)??0,currency:le(t.currency)??"usd",precision:ae(t.precision)??3,address:le(t.address),error:le(t.error),pendingRewards:ae(t.pendingRewards),pendingRewardsFiat:ae(t.pendingRewardsFiat),liquid:ae(t.liquid),liquidFiat:ae(t.liquidFiat),savings:ae(t.savings),savingsFiat:ae(t.savingsFiat),staked:ae(t.staked),stakedFiat:ae(t.stakedFiat),iconUrl:le(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:ae(t.apr)}}function Cl(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let i of ["wallets","tokens","assets","items","portfolio","balances"]){let o=n[i];if(Array.isArray(o))return o}}return []}function Tl(e){if(!e||typeof e!="object")return;let t=e;return le(t.username)??le(t.name)??le(t.account)}function to(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${M.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!i.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${i.status})`);let o=await i.json(),s=Cl(o).map(a=>kl(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:Tl(o)??e,currency:le(o?.fiatCurrency??o?.currency)?.toUpperCase(),wallets:s}}})}function Qt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(ve().queryKey),r=b().getQueryData(N(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:0};let o=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(i)?i:t?t.base/t.quote:0,accountBalance:o+s,parts:[{name:"current",balance:o},{name:"savings",balance:s}]}}})}function ro(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(N(e).queryKey),r=b().getQueryData(ve().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:C(t.hbd_balance).amount+C(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:C(t.hbd_balance).amount},{name:"savings",balance:C(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Il(e){let u=9.5-(e.headBlock-7e6)/25e4*.01;u<.95&&(u=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*u*p/f).toFixed(3)}function no(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(ve()),await b().prefetchQuery(N(e));let t=b().getQueryData(ve().queryKey),r=b().getQueryData(N(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),i=Number.parseFloat(n?.latest??""),o=Number.isFinite(i)?i:t.base/t.quote,s=C(r.vesting_shares).amount,a=C(r.delegated_vesting_shares).amount,u=C(r.received_vesting_shares).amount,p=C(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=Zn(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ve(s,t.hivePerMVests).toFixed(3),y=+Ve(a,t.hivePerMVests).toFixed(3),h=+Ve(u,t.hivePerMVests).toFixed(3),O=+Ve(l,t.hivePerMVests).toFixed(3),x=+Ve(f,t.hivePerMVests).toFixed(3),A=Math.max(m-O,0),P=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:o,accountBalance:+A.toFixed(3),apr:Il(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+P.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:h},...O>0?[{name:"pending_power_down",balance:+O.toFixed(3)}]:[],...x>0&&x!==O?[{name:"next_power_down",balance:+x.toFixed(3)}]:[]]}}})}var K=re.operations,Yr={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay],"":[]};var IT=Object.keys(re.operations);var io=re.operations,BT=io,NT=Object.entries(io).reduce((e,[t,r])=>(e[r]=t,e),{});var oo=re.operations;function Kl(e){return Object.prototype.hasOwnProperty.call(oo,e)}function ft(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),i=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),o=new Set;r||n.forEach(a=>{if(a in Yr){Yr[a].forEach(u=>o.add(u));return}Kl(a)&&o.add(oo[a]);});let s=Ml(Array.from(o));return {filterKey:i,filterArgs:s}}function Xr(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Bl(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Nl(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function Ml(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await g("condenser_api.get_account_history",[e,s,Nl(Number(s),t),...n])).map(u=>({num:u[0],type:u[1].op[0],timestamp:u[1].timestamp,trx_id:u[1].trx_id,...u[1].op[1]})),select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return C(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=C(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return C(p.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return o.has(p.type)}}))})})}function zT(e,t=20,r=[]){let{filterKey:n}=ft(r),i=Xr(r);return infiniteQueryOptions({...Ht(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:s})=>({pageParams:s,pages:o.map(a=>a.filter(u=>{switch(u.type){case "author_reward":case "comment_benefactor_reward":return C(u.hbd_payout).amount>0;case "claim_reward_balance":return C(u.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return C(u.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return C(u.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=C(u.amount);return ["HBD"].includes(f.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return i.has(u.type)}}))})})}function eR(e,t=20,r=[]){let{filterKey:n}=ft(r),i=new Set(Array.isArray(r)?r:[r]),o=i.has("")||i.size===0;return infiniteQueryOptions({...Ht(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return C(p.vesting_payout).amount>0;case "claim_reward_balance":return C(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(C(p.amount).symbol);case "fill_recurrent_transfer":let m=C(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return o||i.has(p.type)}}))})})}function so(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Zr(e,t){return new Date(e.getTime()-t*1e3)}function iR(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,so(t),so(r)])).map(({hive:i,non_hive:o,open:s})=>({close:o.close/i.close,open:o.open/i.open,low:o.low/i.low,high:o.high/i.high,volume:i.volume,time:new Date(s)})),initialPageParam:[Zr(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[Zr(n,Math.max(100*e,28800)),Zr(n,e)]})}function cR(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function dR(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function hR(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>C(n.vesting_shares).amount-C(r.vesting_shares).amount)})}function vR(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function xR(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function CR(e,t,r){let n=i=>i.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function qR(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),i=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:i[0]?i[0].non_hive.open/i[0].hive.open:0,high:i[0]?i[0].non_hive.high/i[0].hive.high:0,low:i[0]?i[0].non_hive.low/i[0].hive.low:0,percent:i[0]?100-i[0].non_hive.open/i[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function BR(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:i})=>{let o=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await o(s,{signal:i});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ao(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function HR(e=1e3,t,r){let n=r??new Date,i=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,i.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[ao(i),ao(n),e])})}function LR(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function zR(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function ZR(e,t,r){return v(["market","limit-order-create"],e,n=>[Kt(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function mt(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function sF(e,t,r,n){let i=_(),o=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await i(o);return mt(s)}async function co(e){if(e==="hbd")return 1;let t=_(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await mt(n)).hive_dollar[e]}async function aF(e,t){let n=await _()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return mt(n)}async function cF(){let t=await _()(d.privateApiHost+"/private-api/market-data/latest");return mt(t)}async function uF(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return mt(t)}var ed={"Content-type":"application/json"};async function td(e){let t=_(),r=M.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:ed});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ee(e,t){try{return await td(e)}catch{return t}}async function dF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,i]=await Promise.all([Ee({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ee({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),o=a=>a.sort((u,p)=>{let l=Number(u.price??0);return Number(p.price??0)-l}),s=a=>a.sort((u,p)=>{let l=Number(u.price??0),f=Number(p.price??0);return l-f});return {buy:o(n),sell:s(i)}}async function fF(e,t=50){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function mF(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[i,o]=await Promise.all([Ee({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ee({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=i.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),u=o.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...u].sort((p,l)=>l.timestamp-p.timestamp)}async function rd(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Ee({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function Ye(e,t){return rd(t,e)}async function Ut(e){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Vt(e){return Ee({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function uo(e,t,r,n){let i=_(),o=M.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",o);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await i(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function po(e,t="daily"){let r=_(),n=M.getValidatedBaseUrl(),i=new URL("/private-api/engine-chart-api",n);i.searchParams.set("symbol",e),i.searchParams.set("interval",t);let o=await r(i.toString(),{headers:{"Content-type":"application/json"}});if(!o.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${o.status}`);return await o.json()}async function lo(e){let t=_(),r=M.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function jt(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ut(e)})}function vF(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ye()})}function fo(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Vt(e)})}function kF(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return uo(e,t,r,n)},getNextPageParam:(n,i,o)=>(n?.length??0)===r?o+r:void 0,getPreviousPageParam:(n,i,o)=>o>0?o-r:void 0})}function FF(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>po(e,t)})}function KF(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await lo(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function mo(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ye(e,t)})}function Xe(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:i,suffix:o}=r,s="";i&&(s+=i+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,u=typeof a=="string"?parseFloat(a):a;return s+=u.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),o&&(s+=" "+o),s}var Lt=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${Xe(this.stake,{fractionDigits:this.precision})} + ${Xe(this.delegationsIn,{fractionDigits:this.precision})} - ${Xe(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():Xe(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():Xe(this.balance,{fractionDigits:this.precision})};function WF(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await Ut(e),i=await Vt(n.map(p=>p.symbol)),o=t?t.base/t.quote:0,s=Array.isArray(r)?r:[],a=n.map(p=>p.symbol).filter(p=>p!=="SWAP.HIVE"&&!s.some(l=>l.symbol===p)),u=[...s,...a.length?await Ye(void 0,a):[]];return n.map(p=>{let l=i.find(x=>x.symbol===p.symbol),f;if(l?.metadata)try{f=JSON.parse(l.metadata);}catch{f=void 0;}let m=u.find(x=>x.symbol===p.symbol),y=Number(m?.lastPrice??"0"),h=Number(p.balance),O=p.symbol==="SWAP.HIVE"?o*h:y===0?0:Number((y*o*h).toFixed(10));return new Lt({symbol:p.symbol,name:l?.name??p.symbol,icon:f?.icon??"",precision:l?.precision??0,stakingEnabled:l?.stakingEnabled??false,delegationEnabled:l?.delegationEnabled??false,balance:p.balance,stake:p.stake,delegationsIn:p.delegationsIn,delegationsOut:p.delegationsOut,usdValue:O})})},enabled:!!e})}function go(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=b(),n=Qt(e);await r.prefetchQuery(n);let i=r.getQueryData(n.queryKey),o=await r.ensureQueryData(fo([t])),s=await r.ensureQueryData(jt(e)),a=await r.ensureQueryData(mo(void 0,t)),u=o?.find(x=>x.symbol===t),p=s?.find(x=>x.symbol===t),f=+(a?.find(x=>x.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),O=[{name:"liquid",balance:m},{name:"staked",balance:y}];return h>0&&O.push({name:"unstaking",balance:h}),{name:t,title:u?.name??"",price:f===0?0:Number(f*(i?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:O}}})}function gt(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let i=await n.json(),o=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!o.ok)throw new Error(`Failed to fetch point transactions: ${o.status}`);let s=await o.json();return {points:i.points,uPoints:i.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function yo(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(gt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(gt(e).queryKey)?.points??0)})})}function lq(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:i,type:o,amount:s,id:a,sender:u,receiver:p,memo:l})=>({created:new Date(i),type:o,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:u??void 0,to:p??void 0,memo:l??void 0}))})}function Pq(e,t,r={refetch:false}){let n=b(),i=r.currency??"usd",o=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||i==="usd")return p;try{let l=await co(i);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${i}:`,l),p}},a=to(e,i,true),u=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,h=m.value;if(typeof h=="string"){let x=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(x){let A=Math.abs(Number.parseFloat(x[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:A}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:A}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:A});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,i],queryFn:async()=>{let p=await u();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await o(Qt(e));else if(t==="HP")l=await o(no(e));else if(t==="HBD")l=await o(ro(e));else if(t==="POINTS")l=await o(yo(e));else if((await n.ensureQueryData(jt(e))).some(m=>m.symbol===t))l=await o(go(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var yd=(A=>(A.Transfer="transfer",A.TransferToSavings="transfer-saving",A.WithdrawFromSavings="withdraw-saving",A.Delegate="delegate",A.PowerUp="power-up",A.PowerDown="power-down",A.WithdrawRoutes="withdraw-routes",A.ClaimInterest="claim-interest",A.Swap="swap",A.Convert="convert",A.Gift="gift",A.Promote="promote",A.Claim="claim",A.Buy="buy",A.Stake="stake",A.Unstake="unstake",A.Undelegate="undelegate",A))(yd||{});function Cq(e,t,r){return v(["wallet","transfer"],e,n=>[Be(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Iq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ge(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Mq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[pt(e,n.delegatee,n.vestingShares)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function jq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[lt(e,n.toAccount,n.percent,n.autoVest)],async(n,i)=>{await S(t?.adapter,r,[c.wallet.withdrawRoutes(e),c.accounts.full(e),c.accounts.full(i.toAccount)]);},t,"active",{broadcastMode:r})}function Gq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Zq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[We(e,n.to,n.amount,n.memo)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function iI(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ne(e,n.to,n.amount,n.memo,n.requestId)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function uI(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[ct(e,n.to,n.amount)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function mI(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ut(e,n.vestingShares)],async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wI(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?vr(e,n.amount,n.requestId):dt(e,n.amount,n.requestId)],async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function OI(e,t,r){return v(["wallet","claim-interest"],e,n=>at(e,n.to,n.amount,n.memo,n.requestId),async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var hd=5e3,$t=new Map;function CI(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Br(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",i=[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],c.assets.hiveGeneralInfo(e),c.assets.hbdGeneralInfo(e),c.assets.hivePowerGeneralInfo(e)],o=$t.get(n);o&&(clearTimeout(o),$t.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(i.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{$t.delete(n);}},hd);$t.set(n,s);},t,"posting",{broadcastMode:r})}function qI(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function BI(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function HI(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function LI(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let i=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function zI(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let i=JSON.stringify(n.tokens.map(o=>({symbol:o})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:i}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function ZI(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let i,o;n.action==="cancel"?(o="cancel",i={type:n.orderType,id:n.orderId}):(o=n.action,i={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:o,contractPayload:i});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await S(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _d(e,t,r){let{from:n,to:i="",amount:o="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Be(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Ne(n,i,o,s,a)];case "power-up":return [ct(n,i,o)]}break;case "HBD":switch(t){case "transfer":return [Be(n,i,o,s)];case "transfer-saving":return [We(n,i,o,s)];case "withdraw-saving":return [Ne(n,i,o,s,a)];case "claim-interest":return at(n,i,o,s,a);case "convert":return [dt(n,o,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ut(n,o)];case "delegate":return [pt(n,i,o)];case "withdraw-routes":return [lt(r.from_account??n,r.to_account??i,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ge(n,i,o,s)];break}return null}function wd(e,t,r){let{from:n,to:i="",amount:o=""}=r,s=typeof o=="string"&&o.includes(" ")?o.split(" ")[0]:String(o);switch(t){case "transfer":return [Me(n,"transfer",{symbol:e,to:i,quantity:s,memo:r.memo??""})];case "stake":return [Me(n,"stake",{symbol:e,to:i,quantity:s})];case "unstake":return [Me(n,"unstake",{symbol:e,to:i,quantity:s})];case "delegate":return [Me(n,"delegate",{symbol:e,to:i,quantity:s})];case "undelegate":return [Me(n,"undelegate",{symbol:e,from:i,quantity:s})];case "claim":return [Ar(n,[e])]}return null}function bd(e){return e==="claim"?"posting":"active"}function oD(e,t,r,n,i){let{mutateAsync:o}=ze.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=_d(t,r,s);if(a)return a;let u=wd(t,r,s);if(u)return u;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{o();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{b().invalidateQueries({queryKey:a});});},5e3);},n,bd(r),{broadcastMode:i})}function uD(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:i})=>[Pr(e,n,i)],async(n,i)=>{await S(t?.adapter,r,[c.accounts.full(e),c.accounts.full(i.to),c.resourceCredits.account(e),c.resourceCredits.account(i.to)]);},t,"active",{broadcastMode:r})}function fD(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:i})=>[Er(e,n,i)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function hD(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Sr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function Ad(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function PD(e){return infiniteQueryOptions({queryKey:c.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ee("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(Ad),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function OD(e,t,r,n="vests",i="desc"){return queryOptions({queryKey:c.witnesses.voters(e,t,r,n,i),queryFn:async({signal:o})=>await ee("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:i},void 0,void 0,o),enabled:!!e,staleTime:6e4})}function xD(e){return queryOptions({queryKey:c.witnesses.voterCount(e),queryFn:async()=>await ee("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Pd=(h=>(h[h.CHECKIN=10]="CHECKIN",h[h.LOGIN=20]="LOGIN",h[h.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",h[h.POST=100]="POST",h[h.COMMENT=110]="COMMENT",h[h.VOTE=120]="VOTE",h[h.REBLOG=130]="REBLOG",h[h.DELEGATION=150]="DELEGATION",h[h.REFERRAL=160]="REFERRAL",h[h.COMMUNITY=170]="COMMUNITY",h[h.TRANSFER_SENT=998]="TRANSFER_SENT",h[h.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",h[h.MINTED=991]="MINTED",h[h.BURNED=997]="BURNED",h))(Pd||{});async function xd(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await _()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),o=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(o)}catch{return {message:o,code:n.status}}let s=o&&i.includes("json")?`: ${o.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!i.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${i||"empty"}" response (status ${n.status})`);try{return JSON.parse(o)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function FD(e,t,r,n){let{mutateAsync:i}=ze.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>xd(e,t),onError:n,onSuccess:()=>{i(),b().setQueryData(gt(e).queryKey,o=>o&&{...o,points:(parseFloat(o.points)+parseFloat(o.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var _o=/(^|\s)author:([^\s]+)/g,wo=/(^|\s)type:([^\s]+)/g,bo=/(^|\s)category:([^\s]+)/g,vo=/(^|\s)tag:([^\s]+)/g;var Po=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Po||{}),ID=5,DD=100;function Oo(e){return e.trim().split(/\s+/)[0]??""}function Ed(e){return Oo(e).replace(/^@+/,"").toLowerCase()}function Sd(e){return Oo(e).replace(/^#+/,"").toLowerCase()}function kd(e){let t=new Set;return e.split(/[\s,]+/).map(r=>r.replace(/^#+/,"").toLowerCase()).filter(r=>r===""||t.has(r)?false:(t.add(r),true))}function KD({search:e="",author:t="",type:r="",category:n="",tags:i=[]}){let o=e.trim().replace(/\s+/g," "),s=Ed(t),a=Sd(n),u=kd(Array.isArray(i)?i.join(","):i),p=[o];return s&&p.push(`author:${s}`),r&&p.push(`type:${r}`),a&&p.push(`category:${a}`),u.length>0&&p.push(`tag:${u.join(",")}`),{q:p.filter(l=>l!=="").join(" "),search:o,author:s,type:r,category:a,tags:u}}var Ao=class{query="";search="";author="";type="";category="";tags=[];constructor(t){this.query=t,this.search=t,this.grabAuthor(),this.grabType(),this.grabCategory(),this.grabTags(),this.grabSearch();}grab=t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""};grabAuthor=()=>{this.author=this.grab(_o);};grabType=()=>{let t=this.grab(wo);Object.values(Po).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(bo);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(vo)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([_o,wo,bo,vo].forEach(t=>{this.search=this.search.replace(t,"$1");});this.search.indexOf(" ")!==-1;)this.search=this.search.replace(" "," ");this.search=this.search.trim();}};async function Ae(e,t){let n=await(async()=>{let i;try{i=await e.text();}catch{return}if(i!=="")try{return JSON.parse(i)}catch{return e.ok?void 0:i}})();if(!e.ok){let i=new Error(`Request failed with status ${e.status}`);throw i.status=e.status,i.data=n,i}if(n===void 0||t!==void 0&&!t(n))throw new Error("Response body was empty, invalid JSON, or not the expected shape");return n}function Se(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var Td=isServer?0:3;function yt(e,t){let{status:r}=t,n=r===408||r===429;return r!==void 0&&r>=400&&r<500&&!n?false:e{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let u=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(be,s)});return Ae(u,Se)},retry:yt})}function WD(e,t,r=true){return infiniteQueryOptions({queryKey:c.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:i})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let o,s=new Date;switch(t){case "today":o=new Date(s.getTime()-1440*60*1e3);break;case "week":o=new Date(s.getTime()-10080*60*1e3);break;case "month":o=new Date(s.getTime()-720*60*60*1e3);break;case "year":o=new Date(s.getTime()-365*24*60*60*1e3);break;default:o=void 0;}let a="* type:post",u=e==="rising"?"children":e,p=o?o.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:u,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:we(be,i)});return Ae(y,Se)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:yt})}async function YD(e,t,r,n,i,o,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),i&&(a.scroll_id=i),o&&(a.votes=o);let p=await _()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:we(be,s)});return Ae(p,Se)}async function xo(e,t,r=be){let i=await _()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:we(r,t)});return Ae(i,Se)}async function XD(e,t){let n=await _()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:we(be,t)}),i=await Ae(n,Array.isArray);return i?.length>0?i:[e]}var Id=4368*60*60*1e3,Dd=4,Kd=3e3,Bd=2e3,Nd=4e3,nK=2;function Md(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Qd(e){let t=5381;for(let r=0;r>>0).toString(36)}function iK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),i=Md(e.body??"",Kd),o=Qd(`${t}|${n.join(",")}|${i}`);return queryOptions({queryKey:c.search.similarEntries(e.author,e.permlink,o),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Id).toISOString().slice(0,19),u=await xo({author:e.author,permlink:e.permlink,title:t,body:i,tags:n,since:a},s,typeof window>"u"?Bd:Nd),p=[],l=new Set;for(let f of u.results){if(p.length>=Dd)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function pK(e,t=5){let r=e.trim();return queryOptions({queryKey:c.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:qt(n)},enabled:!!r})}function gK(e,t=10){let r=e.trim();return queryOptions({queryKey:c.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(i=>i.name).filter(i=>i!==""&&!i.startsWith("hive-")).slice(0,t),enabled:!!r})}function vK(e,t,r,n,i,o){return infiniteQueryOptions({queryKey:c.search.api(e,t,r,n,i,o),queryFn:async({pageParam:s,signal:a})=>{let u={q:e,sort:t,hide_low:r};n&&(u.since=n),s&&(u.scroll_id=s),i!==void 0&&(u.votes=i),o&&(u.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(u),signal:we(be,a)});return Ae(p,Se)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:yt})}function xK(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function $d(e){let r=await _()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let i=n?.message??`Failed to fetch support settings: ${r.status}`,o=new Error(i);throw o.status=r.status,o.data=n,o}return await r.json()}function CK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:c.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return $d(t)},enabled:!!r&&!!t})}async function zd(e,t){let n=await _()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let i;try{i=await n.json();}catch{}let o=i?.message??`Failed to update support settings: ${n.status}`,s=new Error(o);throw s.status=n.status,s.data=i,s}return await n.json()}function Jd(e,t,r){return e.setQueryData(c.support.settings(t),r),e.invalidateQueries({queryKey:c.support.settings(t)})}function IK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async i=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return zd(t,i)},onSuccess(i){n&&Jd(r,n,i);}})}function NK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function UK(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function $K(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function JK(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function eB(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function iB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:i})=>[Ur(e,n,i)],async(n,{account:i})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.promotions.boostPlusAccounts(i)]);},t,"active",{broadcastMode:r})}function cB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Vr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function lB(e){let r=await _()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let i;try{i=await r.json();}catch{i=void 0;}let o=new Error(`Failed to refresh token: ${r.status}`);throw o.status=r.status,o.data=i,o}return await r.json()}var nf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function gB(){return queryOptions({queryKey:c.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(nf,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(` +`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var hB=1.1,of=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(of||{});function _B(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function cf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,i=t.map(a=>{let u=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:u?{total_votes:u.total_votes??0,hive_hp:u.hive_hp,hive_proxied_hp:u.hive_proxied_hp,hive_hp_incl_proxied:u.hive_hp_incl_proxied??null}:void 0}}),o=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:i,poll_voters:o,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function PB(e,t){return queryOptions({queryKey:c.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?Jn:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,i=await r(n);if(!i.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${i.status}`);let o=await i.json();if(!Array.isArray(o)||!o[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return cf(o[0])}})}function EB(e,t,r){return v(c.polls.vote(),e??"",({pollTrxId:n,choices:i})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:i})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/** * @license bytebuffer.ts (c) 2015 Daniel Wirtz * Backing buffer: ArrayBuffer, Accessor: DataView * Released under the Apache License, Version 2.0 * see: https://github.com/dcodeIO/bytebuffer.ts for details * modified by @xmcl/bytebuffer * And customized for hive-tx - */export{ni as ACCOUNT_OPERATION_GROUPS,Oa as ALL_ACCOUNT_OPERATIONS,Gi as ALL_NOTIFY_TYPES,td as AssetOperation,Om as BROADCAST_INCLUSION_DELAY_MS,xi as BuySellTransactionType,d as CONFIG,N as ConfigManager,We as EcencyAnalytics,Ms as EcencyQueriesManager,Ne as EntriesCacheManagement,Vn as ErrorType,Wr as HIVE_ACCOUNT_OPERATION_GROUPS,uT as HIVE_OPERATION_LIST,dT as HIVE_OPERATION_NAME_BY_ID,lT as HIVE_OPERATION_ORDERS,Ut as HiveEngineToken,ji as HiveSignerIntegration,Te as HiveTxTransaction,_e as INTERNAL_API_TIMEOUT_MS,cD as MAX_SEARCH_QUERY_LENGTH,uD as MAX_SEARCH_TAGS,Nn as Memo,St as NaiMap,Up as NotificationFilter,jp as NotificationViewType,Vp as NotifyTypes,Tc as OPERATION_AUTHORITY_MAP,Ei as OrderIdPrefix,LK as POLLS_PROTOCOL_VERSION,ud as PointTransactionType,Vd as PollPreferredInterpretation,H as PrivateKey,J as PublicKey,xp as QUEST_CATALOG,Ep as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,Np as ROLES,$n as SERVER_GC_TIME_MS,RD as SIMILAR_ENTRIES_MIN_RENDER,vE as STREAK_FREEZE_MAX_OWNED,bE as STREAK_FREEZE_PRICE,$i as SUBSCRIBERS_PAGE_SIZE,ho as SearchQuery,wo as SearchType,Ae as Signature,mi as SortOrder,Wn as Symbol,Kt as THREESPEAK_BENEFICIARY_ACCOUNT,hx as THREESPEAK_BENEFICIARY_WEIGHT,Kx as ThreeSpeakIntegration,ra as accountNameByteLength,Ki as addDraft,qi as addImage,SO as addOptimisticDiscussionEntry,Ni as addSchedule,Dd as applySupportSettingsUpdate,tp as applyVoteCacheUpdate,se as bridgeApiCall,Ln as broadcastJson,Z as broadcastOperations,Hn as broadcastOperationsAsync,Ir as buildAccountCreateOp,Xu as buildAccountUpdate2Op,Yu as buildAccountUpdateOp,ic as buildActiveCustomJsonOp,Mr as buildBoostPlusOp,Oi as buildCancelTransferFromSavingsOp,ec as buildChangeRecoveryAccountOp,Kr as buildClaimAccountOp,it as buildClaimInterestOps,qr as buildClaimRewardBalanceOp,hr as buildCollateralizedConvertOp,Ie as buildCommentOp,De as buildCommentOptionsOp,Hr as buildCommunityRegistrationOp,ct as buildConvertOp,Dr as buildCreateClaimedAccountOp,_r as buildDelegateRcOp,at as buildDelegateVestingSharesOp,gr as buildDeleteCommentOp,wr as buildEngineClaimOp,Me as buildEngineOp,zu as buildFlagPostOp,br as buildFollowOp,Br as buildGrantPostingPermissionOp,ju as buildIgnoreOp,Fr as buildLimitOrderCancelOp,qt as buildLimitOrderCreateOp,Ju as buildLimitOrderCreateOpWithType,nc as buildMultiPointTransferOps,Uu as buildMultiTransferOps,Rr as buildMutePostOp,Gu as buildMuteUserOp,Tr as buildPinPostOp,$e as buildPointTransferOp,oc as buildPostingCustomJsonOp,ei as buildPostingJsonMetadata,lr as buildProfileMetadata,Qr as buildPromoteOp,Or as buildProposalCreateOp,xr as buildProposalVoteOp,Nr as buildRcDelegationOp,yr as buildReblogOp,rc as buildRecoverAccountOp,Vu as buildRecurrentTransferOp,$u as buildRemoveProposalOp,tc as buildRequestAccountRecoveryOp,ki as buildRevokeKeysOp,Zu as buildRevokePostingPermissionOp,pD as buildSearchQuery,vr as buildSetLastReadOps,kr as buildSetRoleOp,ut as buildSetWithdrawVestingRouteOp,Er as buildSubscribeOp,Be as buildTransferFromSavingsOp,Ke as buildTransferOp,Le as buildTransferToSavingsOp,ot as buildTransferToVestingOp,Rt as buildUnfollowOp,Lu as buildUnignoreOp,Sr as buildUnsubscribeOp,Cr as buildUpdateCommunityOp,Wu as buildUpdateProposalOp,mr as buildVoteOp,st as buildWithdrawVestingOp,Pr as buildWitnessProxyOp,Ar as buildWitnessVoteOp,Rp as buyStreakFreezeRequest,xt as calculateRCMana,ur as calculateVPMana,ee as callREST,g as callRPC,Qe as callRPCBroadcast,Pt as callWithQuorum,zA as canRevokeFromAuthority,$y as checkFavoriteQueryOptions,Py as checkUsernameWalletsPendingQueryOptions,pd as claimPointsRequest,Gr as collectRequestedOperations,Nm as decodeObj,dc as dedupeAndSortKeyAuths,Mi as deleteDraft,Di as deleteImage,Qi as deleteSchedule,_P as downVotingPower,_E as earnsQuestContentCredit,Mm as encodeObj,wx as enforceThreeSpeakBeneficiary,nE as estimateRcPrecheck,Xn as extractAccountProfile,Os as formatError,ze as formattedNumber,Jk as getAccountDelegationsQueryOptions,M as getAccountFullQueryOptions,SS as getAccountNotificationsInfiniteQueryOptions,th as getAccountPendingRecoveryQueryOptions,dr as getAccountPosts,a_ as getAccountPostsInfiniteQueryOptions,u_ as getAccountPostsQueryOptions,eE as getAccountRcQueryOptions,Jy as getAccountRecoveriesQueryOptions,ah as getAccountReputationsQueryOptions,Fy as getAccountSubscriptionsQueryOptions,iv as getAccountVoteHistoryInfiniteQueryOptions,YF as getAccountWalletAssetInfoQueryOptions,Ug as getAccountsQueryOptions,bv as getAggregatedBalanceQueryOptions,pg as getAiAssistPriceQueryOptions,sg as getAiGeneratePriceQueryOptions,mg as getAiTranscribePriceQueryOptions,uo as getAllHiveEngineTokensQueryOptions,tk as getAnnouncementsQueryOptions,VK as getBadActorsQueryOptions,gv as getBalanceHistoryInfiniteQueryOptions,By as getBookmarksInfiniteQueryOptions,Ky as getBookmarksQueryOptions,kK as getBoostPlusAccountPricesQueryOptions,dK as getBoostPlusPricesQueryOptions,_h as getBotsQueryOptions,w as getBoundFetch,NP as getChainPropertiesQueryOptions,uC as getCollateralizedConversionRequestsQueryOptions,W_ as getCommentHistoryQueryOptions,jw as getCommunities,iS as getCommunitiesQueryOptions,li as getCommunity,cS as getCommunityContextQueryOptions,KS as getCommunityPermissions,mS as getCommunityQueryOptions,vS as getCommunitySubscribersInfiniteQueryOptions,bS as getCommunitySubscribersQueryOptions,DS as getCommunityType,ww as getContentQueryOptions,Pw as getContentRepliesQueryOptions,vD as getControversialRisingInfiniteQueryOptions,iC as getConversionRequestsQueryOptions,no as getCurrencyRate,KR as getCurrencyRates,DR as getCurrencyTokenRate,PR as getCurrentMedianHistoryPriceQueryOptions,Rc as getCustomJsonAuthority,Y_ as getDeletedEntryQueryOptions,ax as getDiscoverCurationQueryOptions,rx as getDiscoverLeaderboardQueryOptions,pi as getDiscussion,e_ as getDiscussionQueryOptions,gi as getDiscussionsQueryOptions,B_ as getDraftsInfiniteQueryOptions,K_ as getDraftsQueryOptions,be as getDynamicPropsQueryOptions,uw as getEntryActiveVotesQueryOptions,Uy as getFavoritesInfiniteQueryOptions,Hy as getFavoritesQueryOptions,_R as getFeedHistoryQueryOptions,Wg as getFollowCountQueryOptions,Xg as getFollowersQueryOptions,ny as getFollowingQueryOptions,Zh as getFragmentsInfiniteQueryOptions,je as getFragmentsQueryOptions,qh as getFriendsInfiniteQueryOptions,U_ as getGalleryImagesQueryOptions,aE as getGameStatusCheckQueryOptions,Yi as getHbdAssetGeneralInfoQueryOptions,PT as getHbdAssetTransactionsQueryOptions,Bt as getHiveAssetGeneralInfoQueryOptions,FT as getHiveAssetMetricQueryOptions,Mt as getHiveAssetTransactionsQueryOptions,KT as getHiveAssetWithdrawalRoutesQueryOptions,vF as getHiveEngineBalancesWithUsdQueryOptions,Hl as getHiveEngineMetrics,UR as getHiveEngineOpenOrders,QR as getHiveEngineOrderBook,co as getHiveEngineTokenGeneralInfoQueryOptions,oo as getHiveEngineTokenMetrics,io as getHiveEngineTokenTransactions,rF as getHiveEngineTokenTransactionsQueryOptions,Nt as getHiveEngineTokensBalances,Ht as getHiveEngineTokensBalancesQueryOptions,Ge as getHiveEngineTokensMarket,zR as getHiveEngineTokensMarketQueryOptions,Qt as getHiveEngineTokensMetadata,ao as getHiveEngineTokensMetadataQueryOptions,sF as getHiveEngineTokensMetricsQueryOptions,HR as getHiveEngineTradeHistory,so as getHiveEngineUnclaimedRewards,pF as getHiveEngineUnclaimedRewardsQueryOptions,aR as getHiveHbdStatsQueryOptions,Ux as getHivePoshLinksQueryOptions,Xi as getHivePowerAssetGeneralInfoQueryOptions,kT as getHivePowerAssetTransactionsQueryOptions,QT as getHivePowerDelegatesInfiniteQueryOptions,LT as getHivePowerDelegatingsQueryOptions,BR as getHivePrice,V_ as getImagesInfiniteQueryOptions,H_ as getImagesQueryOptions,CC as getIncomingRcQueryOptions,IR as getMarketData,lR as getMarketDataQueryOptions,nR as getMarketHistoryQueryOptions,ZT as getMarketStatisticsQueryOptions,uy as getMutedUsersQueryOptions,Al as getNextAccountHistoryPageParam,Jb as getNormalizePostQueryOptions,m0 as getNotificationSetting,d0 as getNotifications,jS as getNotificationsInfiniteQueryOptions,YS as getNotificationsSettingsQueryOptions,QS as getNotificationsUnreadCountQueryOptions,bC as getOpenOrdersQueryOptions,qc as getOperationAuthority,zT as getOrderBookQueryOptions,xC as getOutgoingRcDelegationsInfiniteQueryOptions,lx as getPageStatsQueryOptions,po as getPointsAssetGeneralInfoQueryOptions,NF as getPointsAssetTransactionsQueryOptions,dt as getPointsQueryOptions,YK as getPollQueryOptions,Ji as getPortfolioQueryOptions,Wa as getPost,Vw as getPostHeader,kw as getPostHeaderQueryOptions,si as getPostQueryOptions,tb as getPostTipsQueryOptions,ci as getPostsRanked,y_ as getPostsRankedInfiniteQueryOptions,h_ as getPostsRankedQueryOptions,Ov as getProMembersQueryOptions,Tt as getProfiles,cv as getProfilesQueryOptions,OK as getPromotePriceQueryOptions,y0 as getPromotedPost,nw as getPromotedPostsQuery,Fc as getProposalAuthority,bk as getProposalQueryOptions,Tk as getProposalVotesInfiniteQueryOptions,Ok as getProposalsQueryOptions,b as getQueryClient,wE as getQuestCatalogEntry,yE as getQuestsQueryOptions,bK as getRcDelegationActiveQueryOptions,yK as getRcDelegationPricesQueryOptions,Jx as getRcStatsQueryOptions,S_ as getRebloggedByQueryOptions,A_ as getReblogsQueryOptions,qC as getReceivedVestingSharesQueryOptions,BC as getRecurrentTransfersQueryOptions,Ph as getReferralsInfiniteQueryOptions,Sh as getReferralsStatsQueryOptions,Ww as getRelationshipBetweenAccounts,ri as getRelationshipBetweenAccountsQueryOptions,PP as getRequiredAuthority,tg as getRewardFundQueryOptions,RS as getRewardedCommunitiesQueryOptions,dC as getSavingsWithdrawFromQueryOptions,F_ as getSchedulesInfiniteQueryOptions,R_ as getSchedulesQueryOptions,MD as getSearchAccountQueryOptions,_y as getSearchAccountsByUsernameQueryOptions,zD as getSearchApiInfiniteQueryOptions,Mh as getSearchFriendsQueryOptions,ZD as getSearchPathQueryOptions,VD as getSearchTopicsQueryOptions,gb as getShortsFeedQueryOptions,FD as getSimilarEntriesQueryOptions,ok as getSpotlightsQueryOptions,$x as getStatsQueryOptions,$w as getSubscribers,Lw as getSubscriptions,nK as getSupportSettingsQueryOptions,Rd as getSupportSettingsRequest,gR as getTradeHistoryQueryOptions,gh as getTransactionsInfiniteQueryOptions,Vh as getTrendingTagsQueryOptions,zh as getTrendingTagsWithStatsQueryOptions,fw as getUserPostVoteQueryOptions,Ik as getUserProposalVotesQueryOptions,eC as getVestingDelegationExpirationsQueryOptions,$k as getVestingDelegationsQueryOptions,_i as getVisibleFirstLevelThreadItems,Hb as getWavesByAccountQueryOptions,Ab as getWavesByHostQueryOptions,Sb as getWavesByTagQueryOptions,cb as getWavesFeedQueryOptions,Fb as getWavesFollowingQueryOptions,pb as getWavesLatestFeedQueryOptions,Lb as getWavesTrendingAuthorsQueryOptions,Kb as getWavesTrendingTagsQueryOptions,yC as getWithdrawRoutesQueryOptions,ZI as getWitnessVoterCountQueryOptions,XI as getWitnessVotersPageQueryOptions,YI as getWitnessesInfiniteQueryOptions,lp as hasThreeSpeakEmbed,x as hiveTxConfig,re as hiveTxUtils,NK as hsTokenRenew,S as invalidateAfterBroadcast,Gn as isCommunity,zn as isEmptyDate,Es as isInfoError,Ss as isNetworkError,Ve as isQueryableAccountName,xs as isResourceCreditsError,_x as isThreeSpeakBeneficiary,ep as isVoteAlreadyReflected,Qn as isWif,Ns as isWrappedResponse,my as lookupAccountsQueryOptions,Km as makeQueryClient,$K as mapMetaChoicesToPollChoices,bi as mapThreadItemsToWaveEntries,Fi as markNotifications,Sp as measureQuestContentLength,Hi as moveSchedule,di as normalizePost,ld as normalizeSearchAuthor,dd as normalizeSearchCategory,fd as normalizeSearchTags,oe as normalizeToWrappedResponse,me as normalizeWaveEntryFromApi,h0 as onboardEmail,Ct as parseAccounts,C as parseAsset,He as parseChainError,ta as parsePostingMetadataRoot,qe as parseProfileMetadata,Zn as pickRicherMetadataSnapshot,wP as powerRechargeTime,xv as proMembersSet,bP as rcPower,Ui as removeOptimisticDiscussionEntry,Pl as resolveAccountHistoryLimit,pt as resolveHiveOperationFilters,ai as resolvePost,Vi as restoreDiscussionSnapshots,CO as restoreEntryInCache,qS as roleMap,f0 as saveNotificationSetting,xD as search,ED as searchPath,bD as searchQueryOptions,um as sha256,ye as shouldTriggerAuthFallback,c0 as signUp,bo as similar,Ga as sortDiscussions,p0 as subscribeEmail,mu as toEntryArray,Bi as updateDraft,kO as updateEntryInCache,Id as updateSupportSettingsRequest,Ii as uploadImage,g0 as uploadImageWithSignature,_A as useAccountFavoriteAdd,OA as useAccountFavoriteDelete,Kv as useAccountRelationsUpdate,tP as useAccountRevokeKey,QA as useAccountRevokePosting,Rv as useAccountUpdate,Si as useAccountUpdateKeyAuths,IA as useAccountUpdatePassword,WA as useAccountUpdateRecovery,A0 as useAddDraft,WP as useAddFragment,Z0 as useAddImage,M0 as useAddSchedule,Ag as useAiAssist,Eg as useAiTranscribe,lA as useBookmarkAdd,gA as useBookmarkDelete,FK as useBoostPlus,v as useBroadcastMutation,xE as useBuyStreakFreeze,oP as useClaimAccount,PI as useClaimEngineRewards,Xq as useClaimInterest,sD as useClaimPoints,nI as useClaimRewards,OO as useComment,Wq as useConvert,fP as useCreateAccount,MO as useCrossPost,aI as useDelegateEngineToken,BI as useDelegateRc,fq as useDelegateVestingShares,IO as useDeleteComment,q0 as useDeleteDraft,iO as useDeleteImage,V0 as useDeleteSchedule,e0 as useEditFragment,SI as useEngineMarketOrder,nA as useFollow,dE as useGameClaim,wg as useGenerateImage,cP as useGrantPostingPermission,RR as useLimitOrderCancel,SR as useLimitOrderCreate,dk as useMarkNotificationsRead,G0 as useMoveSchedule,BE as useMutePost,ZE as usePinPost,eB as usePollVote,$O as usePromote,Uk as useProposalCreate,Mk as useProposalVote,KK as useRcDelegation,bO as useReblog,Vr as useRecordActivity,zE as useRegisterCommunityRewards,s0 as useRemoveFragment,HE as useSetCommunityRole,yk as useSetLastRead,wq as useSetWithdrawVestingRoute,DP as useSignOperationByHivesigner,kP as useSignOperationByKey,RP as useSignOperationByKeychain,gI as useStakeEngineToken,CE as useSubscribeCommunity,nq as useTransfer,Aq as useTransferEngineToken,Fq as useTransferFromSavings,uq as useTransferPoint,Sq as useTransferToSavings,Bq as useTransferToVesting,lI as useUndelegateEngineToken,aA as useUnfollow,_I as useUnstakeEngineToken,qE as useUnsubscribeCommunity,LE as useUpdateCommunity,S0 as useUpdateDraft,UO as useUpdateReply,uK as useUpdateSupportSettings,uO as useUploadImage,gO as useVote,qI as useWalletOperation,Uq as useWithdrawVesting,LI as useWitnessProxy,HI as useWitnessVote,l0 as usrActivity,op as validatePostCreating,oi as verifyPostOnAlternateNode,Ue as vestsToHp,hP as votingPower,Cc as votingRshares,vP as votingValue,we as withTimeoutSignal};//# sourceMappingURL=index.mjs.map + */export{ai as ACCOUNT_OPERATION_GROUPS,Ca as ALL_ACCOUNT_OPERATIONS,Zi as ALL_NOTIFY_TYPES,yd as AssetOperation,Mm as BROADCAST_INCLUSION_DELAY_MS,Ci as BuySellTransactionType,d as CONFIG,M as ConfigManager,ze as EcencyAnalytics,Vs as EcencyQueriesManager,Qe as EntriesCacheManagement,Wn as ErrorType,Yr as HIVE_ACCOUNT_OPERATION_GROUPS,IT as HIVE_OPERATION_LIST,NT as HIVE_OPERATION_NAME_BY_ID,BT as HIVE_OPERATION_ORDERS,Lt as HiveEngineToken,Gi as HiveSignerIntegration,Re as HiveTxTransaction,be as INTERNAL_API_TIMEOUT_MS,DD as MAX_SEARCH_QUERY_LENGTH,ID as MAX_SEARCH_TAGS,Vn as Memo,Tt as NaiMap,nl as NotificationFilter,ol as NotificationViewType,il as NotifyTypes,Du as OPERATION_AUTHORITY_MAP,Ti as OrderIdPrefix,hB as POLLS_PROTOCOL_VERSION,Pd as PointTransactionType,of as PollPreferredInterpretation,H as PrivateKey,J as PublicKey,Qp as QUEST_CATALOG,Hp as QUEST_MIN_CONTENT_LENGTH,c as QueryKeys,zi as RC_RESOURCE_NAMES,el as ROLES,Jn as SERVER_GC_TIME_MS,nK as SIMILAR_ENTRIES_MIN_RENDER,WE as STREAK_FREEZE_MAX_OWNED,$E as STREAK_FREEZE_PRICE,Yi as SUBSCRIBERS_PAGE_SIZE,Ao as SearchQuery,Po as SearchType,Pe as Signature,_i as SortOrder,Yn as Symbol,Mt as THREESPEAK_BENEFICIARY_ACCOUNT,qx as THREESPEAK_BENEFICIARY_WEIGHT,Xx as ThreeSpeakIntegration,aa as accountNameByteLength,Qi as addDraft,Bi as addImage,VO as addOptimisticDiscussionEntry,Vi as addSchedule,Jd as applySupportSettingsUpdate,sp as applyVoteCacheUpdate,se as bridgeApiCall,zn as broadcastJson,Z as broadcastOperations,Ln as broadcastOperationsAsync,Nr as buildAccountCreateOp,nu as buildAccountUpdate2Op,ru as buildAccountUpdateOp,uu as buildActiveCustomJsonOp,Ur as buildBoostPlusOp,ki as buildCancelTransferFromSavingsOp,ou as buildChangeRecoveryAccountOp,Qr as buildClaimAccountOp,at as buildClaimInterestOps,Br as buildClaimRewardBalanceOp,vr as buildCollateralizedConvertOp,De as buildCommentOp,Ke as buildCommentOptionsOp,Lr as buildCommunityRegistrationOp,dt as buildConvertOp,Mr as buildCreateClaimedAccountOp,Pr as buildDelegateRcOp,pt as buildDelegateVestingSharesOp,wr as buildDeleteCommentOp,Ar as buildEngineClaimOp,Me as buildEngineOp,eu as buildFlagPostOp,Or as buildFollowOp,Hr as buildGrantPostingPermissionOp,zc as buildIgnoreOp,Kr as buildLimitOrderCancelOp,Kt as buildLimitOrderCreateOp,tu as buildLimitOrderCreateOpWithType,cu as buildMultiPointTransferOps,Wc as buildMultiTransferOps,Dr as buildMutePostOp,Zc as buildMuteUserOp,Ir as buildPinPostOp,Ge as buildPointTransferOp,pu as buildPostingCustomJsonOp,ii as buildPostingJsonMetadata,gr as buildProfileMetadata,jr as buildPromoteOp,kr as buildProposalCreateOp,Cr as buildProposalVoteOp,Vr as buildRcDelegationOp,br as buildReblogOp,au as buildRecoverAccountOp,Gc as buildRecurrentTransferOp,Yc as buildRemoveProposalOp,su as buildRequestAccountRecoveryOp,Fi as buildRevokeKeysOp,iu as buildRevokePostingPermissionOp,KD as buildSearchQuery,xr as buildSetLastReadOps,Fr as buildSetRoleOp,lt as buildSetWithdrawVestingRouteOp,Tr as buildSubscribeOp,Ne as buildTransferFromSavingsOp,Be as buildTransferOp,We as buildTransferToSavingsOp,ct as buildTransferToVestingOp,It as buildUnfollowOp,Jc as buildUnignoreOp,Rr as buildUnsubscribeOp,qr as buildUpdateCommunityOp,Xc as buildUpdateProposalOp,_r as buildVoteOp,ut as buildWithdrawVestingOp,Sr as buildWitnessProxyOp,Er as buildWitnessVoteOp,$p as buyStreakFreezeRequest,kt as calculateRCMana,lr as calculateVPMana,ee as callREST,g as callRPC,He as callRPCBroadcast,Et as callWithQuorum,lP as canRevokeFromAuthority,ch as checkFavoriteQueryOptions,My as checkUsernameWalletsPendingQueryOptions,xd as claimPointsRequest,Xr as collectRequestedOperations,Rp as computeResourceCost,Fp as countCommentResourceUsage,eg as decodeObj,hu as dedupeAndSortKeyAuths,Ui as deleteDraft,Mi as deleteImage,ji as deleteSchedule,DP as downVotingPower,LE as earnsQuestContentCredit,Zm as encodeObj,Ix as enforceThreeSpeakBeneficiary,CE as estimateCommentRcCost,Dp as estimateCommentTransactionBytes,xE as estimateRcPrecheck,ri as extractAccountProfile,Cs as formatError,Xe as formattedNumber,AC as getAccountDelegationsQueryOptions,N as getAccountFullQueryOptions,ZS as getAccountNotificationsInfiniteQueryOptions,hh as getAccountPendingRecoveryQueryOptions,yr as getAccountPosts,Pw as getAccountPostsInfiniteQueryOptions,Ow as getAccountPostsQueryOptions,yE as getAccountRcQueryOptions,dh as getAccountRecoveriesQueryOptions,Ph as getAccountReputationsQueryOptions,Gy as getAccountSubscriptionsQueryOptions,bv as getAccountVoteHistoryInfiniteQueryOptions,Pq as getAccountWalletAssetInfoQueryOptions,iy as getAccountsQueryOptions,Kv as getAggregatedBalanceQueryOptions,Eg as getAiAssistPriceQueryOptions,Ag as getAiGeneratePriceQueryOptions,Tg as getAiTranscribePriceQueryOptions,mo as getAllHiveEngineTokensQueryOptions,Sk as getAnnouncementsQueryOptions,gB as getBadActorsQueryOptions,Rv as getBalanceHistoryInfiniteQueryOptions,Zy as getBookmarksInfiniteQueryOptions,Xy as getBookmarksQueryOptions,eB as getBoostPlusAccountPricesQueryOptions,NK as getBoostPlusPricesQueryOptions,Dh as getBotsQueryOptions,_ as getBoundFetch,t0 as getChainPropertiesQueryOptions,IC as getCollateralizedConversionRequestsQueryOptions,ub as getCommentHistoryQueryOptions,sw as getCommunities,TS as getCommunitiesQueryOptions,gi as getCommunity,DS as getCommunityContextQueryOptions,ck as getCommunityPermissions,QS as getCommunityQueryOptions,WS as getCommunitySubscribersInfiniteQueryOptions,$S as getCommunitySubscribersQueryOptions,ak as getCommunityType,I_ as getContentQueryOptions,M_ as getContentRepliesQueryOptions,WD as getControversialRisingInfiniteQueryOptions,TC as getConversionRequestsQueryOptions,co as getCurrencyRate,cF as getCurrencyRates,aF as getCurrencyTokenRate,zR as getCurrentMedianHistoryPriceQueryOptions,Ku as getCustomJsonAuthority,fb as getDeletedEntryQueryOptions,Px as getDiscoverCurationQueryOptions,_x as getDiscoverLeaderboardQueryOptions,mi as getDiscussion,yw as getDiscussionQueryOptions,wi as getDiscussionsQueryOptions,Zw as getDraftsInfiniteQueryOptions,Xw as getDraftsQueryOptions,ve as getDynamicPropsQueryOptions,O_ as getEntryActiveVotesQueryOptions,ih as getFavoritesInfiniteQueryOptions,nh as getFavoritesQueryOptions,LR as getFeedHistoryQueryOptions,uy as getFollowCountQueryOptions,my as getFollowersQueryOptions,wy as getFollowingQueryOptions,g_ as getFragmentsInfiniteQueryOptions,$e as getFragmentsQueryOptions,zh as getFriendsInfiniteQueryOptions,ib as getGalleryImagesQueryOptions,qE as getGameStatusCheckQueryOptions,ro as getHbdAssetGeneralInfoQueryOptions,zT as getHbdAssetTransactionsQueryOptions,Qt as getHiveAssetGeneralInfoQueryOptions,iR as getHiveAssetMetricQueryOptions,Ht as getHiveAssetTransactionsQueryOptions,cR as getHiveAssetWithdrawalRoutesQueryOptions,WF as getHiveEngineBalancesWithUsdQueryOptions,rd as getHiveEngineMetrics,mF as getHiveEngineOpenOrders,dF as getHiveEngineOrderBook,go as getHiveEngineTokenGeneralInfoQueryOptions,po as getHiveEngineTokenMetrics,uo as getHiveEngineTokenTransactions,kF as getHiveEngineTokenTransactionsQueryOptions,Ut as getHiveEngineTokensBalances,jt as getHiveEngineTokensBalancesQueryOptions,Ye as getHiveEngineTokensMarket,vF as getHiveEngineTokensMarketQueryOptions,Vt as getHiveEngineTokensMetadata,fo as getHiveEngineTokensMetadataQueryOptions,FF as getHiveEngineTokensMetricsQueryOptions,fF as getHiveEngineTradeHistory,lo as getHiveEngineUnclaimedRewards,KF as getHiveEngineUnclaimedRewardsQueryOptions,qR as getHiveHbdStatsQueryOptions,iE as getHivePoshLinksQueryOptions,no as getHivePowerAssetGeneralInfoQueryOptions,eR as getHivePowerAssetTransactionsQueryOptions,dR as getHivePowerDelegatesInfiniteQueryOptions,hR as getHivePowerDelegatingsQueryOptions,uF as getHivePrice,ob as getImagesInfiniteQueryOptions,nb as getImagesQueryOptions,tT as getIncomingRcQueryOptions,sF as getMarketData,BR as getMarketDataQueryOptions,CR as getMarketHistoryQueryOptions,xR as getMarketStatisticsQueryOptions,Oy as getMutedUsersQueryOptions,Bl as getNextAccountHistoryPageParam,dv as getNormalizePostQueryOptions,T0 as getNotificationSetting,k0 as getNotifications,yk as getNotificationsInfiniteQueryOptions,Pk as getNotificationsSettingsQueryOptions,dk as getNotificationsUnreadCountQueryOptions,$C as getOpenOrdersQueryOptions,Nu as getOperationAuthority,vR as getOrderBookQueryOptions,YC as getOutgoingRcDelegationsInfiniteQueryOptions,Sx as getPageStatsQueryOptions,yo as getPointsAssetGeneralInfoQueryOptions,lq as getPointsAssetTransactionsQueryOptions,gt as getPointsQueryOptions,PB as getPollQueryOptions,to as getPortfolioQueryOptions,Xa as getPost,ow as getPostHeader,j_ as getPostHeaderQueryOptions,pi as getPostQueryOptions,hb as getPostTipsQueryOptions,fi as getPostsRanked,Fw as getPostsRankedInfiniteQueryOptions,qw as getPostsRankedQueryOptions,Qv as getProMembersQueryOptions,qt as getProfiles,xv as getProfilesQueryOptions,JK as getPromotePriceQueryOptions,F0 as getPromotedPost,w_ as getPromotedPostsQuery,Bu as getProposalAuthority,$k as getProposalQueryOptions,rC as getProposalVotesInfiniteQueryOptions,Jk as getProposalsQueryOptions,b as getQueryClient,jE as getQuestCatalogEntry,UE as getQuestsQueryOptions,$K as getRcDelegationActiveQueryOptions,UK as getRcDelegationPricesQueryOptions,vE as getRcResourceParamsQueryOptions,dE as getRcStatsQueryOptions,Vw as getRebloggedByQueryOptions,Nw as getReblogsQueryOptions,oT as getReceivedVestingSharesQueryOptions,uT as getRecurrentTransfersQueryOptions,Mh as getReferralsInfiniteQueryOptions,Vh as getReferralsStatsQueryOptions,uw as getRelationshipBetweenAccounts,si as getRelationshipBetweenAccountsQueryOptions,MP as getRequiredAuthority,yg as getRewardFundQueryOptions,nk as getRewardedCommunitiesQueryOptions,NC as getSavingsWithdrawFromQueryOptions,Gw as getSchedulesInfiniteQueryOptions,Ww as getSchedulesQueryOptions,pK as getSearchAccountQueryOptions,Dy as getSearchAccountsByUsernameQueryOptions,vK as getSearchApiInfiniteQueryOptions,e_ as getSearchFriendsQueryOptions,xK as getSearchPathQueryOptions,gK as getSearchTopicsQueryOptions,Rb as getShortsFeedQueryOptions,iK as getSimilarEntriesQueryOptions,Rk as getSpotlightsQueryOptions,cE as getStatsQueryOptions,cw as getSubscribers,aw as getSubscriptions,CK as getSupportSettingsQueryOptions,$d as getSupportSettingsRequest,HR as getTradeHistoryQueryOptions,Rh as getTransactionsInfiniteQueryOptions,o_ as getTrendingTagsQueryOptions,l_ as getTrendingTagsWithStatsQueryOptions,C_ as getUserPostVoteQueryOptions,sC as getUserProposalVotesQueryOptions,EC as getVestingDelegationExpirationsQueryOptions,_C as getVestingDelegationsQueryOptions,Pi as getVisibleFirstLevelThreadItems,nv as getWavesByAccountQueryOptions,Nb as getWavesByHostQueryOptions,Vb as getWavesByTagQueryOptions,xb as getWavesFeedQueryOptions,Gb as getWavesFollowingQueryOptions,Eb as getWavesLatestFeedQueryOptions,av as getWavesTrendingAuthorsQueryOptions,Xb as getWavesTrendingTagsQueryOptions,UC as getWithdrawRoutesQueryOptions,xD as getWitnessVoterCountQueryOptions,OD as getWitnessVotersPageQueryOptions,PD as getWitnessesInfiniteQueryOptions,yp as hasThreeSpeakEmbed,E as hiveTxConfig,re as hiveTxUtils,lB as hsTokenRenew,S as invalidateAfterBroadcast,Xn as isCommunity,Zn as isEmptyDate,Rs as isInfoError,Fs as isNetworkError,Le as isQueryableAccountName,Ts as isResourceCreditsError,Dx as isThreeSpeakBeneficiary,op as isVoteAlreadyReflected,jn as isWif,js as isWrappedResponse,Ty as lookupAccountsQueryOptions,Ym as makeQueryClient,_B as mapMetaChoicesToPollChoices,Oi as mapThreadItemsToWaveEntries,Ki as markNotifications,Up as measureQuestContentLength,Li as moveSchedule,yi as normalizePost,Ed as normalizeSearchAuthor,Sd as normalizeSearchCategory,kd as normalizeSearchTags,oe as normalizeToWrappedResponse,me as normalizeWaveEntryFromApi,q0 as onboardEmail,Ft as parseAccounts,C as parseAsset,Ue as parseChainError,sa as parsePostingMetadataRoot,Ie as parseProfileMetadata,ni as pickRicherMetadataSnapshot,IP as powerRechargeTime,Hv as proMembersSet,KP as rcPower,$i as removeOptimisticDiscussionEntry,Nl as resolveAccountHistoryLimit,ft as resolveHiveOperationFilters,li as resolvePost,Wi as restoreDiscussionSnapshots,LO as restoreEntryInCache,ok as roleMap,C0 as saveNotificationSetting,YD as search,XD as searchPath,$D as searchQueryOptions,Pm as sha256,he as shouldTriggerAuthFallback,x0 as signUp,xo as similar,Za as sortDiscussions,E0 as subscribeEmail,wc as toEntryArray,Hi as updateDraft,jO as updateEntryInCache,zd as updateSupportSettingsRequest,Ni as uploadImage,R0 as uploadImageWithSignature,DA as useAccountFavoriteAdd,QA as useAccountFavoriteDelete,Xv as useAccountRelationsUpdate,hP as useAccountRevokeKey,rP as useAccountRevokePosting,Wv as useAccountUpdate,Ri as useAccountUpdateKeyAuths,JA as useAccountUpdatePassword,uP as useAccountUpdateRecovery,N0 as useAddDraft,u0 as useAddFragment,gO as useAddImage,eO as useAddSchedule,Ng as useAiAssist,Ug as useAiTranscribe,SA as useBookmarkAdd,RA as useBookmarkDelete,iB as useBoostPlus,v as useBroadcastMutation,YE as useBuyStreakFreeze,vP as useClaimAccount,zI as useClaimEngineRewards,OI as useClaimInterest,FD as useClaimPoints,CI as useClaimRewards,QO as useComment,wI as useConvert,CP as useCreateAccount,ex as useCrossPost,qI as useDelegateEngineToken,uD as useDelegateRc,Mq as useDelegateVestingShares,JO as useDeleteComment,z0 as useDeleteDraft,bO as useDeleteImage,oO as useDeleteSchedule,y0 as useEditFragment,ZI as useEngineMarketOrder,wA as useFollow,NE as useGameClaim,Ig as useGenerateImage,xP as useGrantPostingPermission,nF as useLimitOrderCancel,ZR as useLimitOrderCreate,Nk as useMarkNotificationsRead,pO as useMoveSchedule,uS as useMutePost,xS as usePinPost,EB as usePollVote,cx as usePromote,mC as useProposalCreate,pC as useProposalVote,cB as useRcDelegation,KO as useReblog,Wr as useRecordActivity,vS as useRegisterCommunityRewards,A0 as useRemoveFragment,fS as useSetCommunityRole,Uk as useSetLastRead,jq as useSetWithdrawVestingRoute,YP as useSignOperationByHivesigner,jP as useSignOperationByKey,WP as useSignOperationByKeychain,HI as useStakeEngineToken,tS as useSubscribeCommunity,Cq as useTransfer,Gq as useTransferEngineToken,iI as useTransferFromSavings,Iq as useTransferPoint,Zq as useTransferToSavings,uI as useTransferToVesting,BI as useUndelegateEngineToken,PA as useUnfollow,LI as useUnstakeEngineToken,oS as useUnsubscribeCommunity,hS as useUpdateCommunity,V0 as useUpdateDraft,ix as useUpdateReply,IK as useUpdateSupportSettings,OO as useUploadImage,RO as useVote,oD as useWalletOperation,mI as useWithdrawVesting,hD as useWitnessProxy,fD as useWitnessVote,S0 as usrActivity,fr as utf8ByteLength,pp as validatePostCreating,je as varintByteLength,ui as verifyPostOnAlternateNode,Ve as vestsToHp,qP as votingPower,Iu as votingRshares,BP as votingValue,we as withTimeoutSignal};//# sourceMappingURL=index.mjs.map //# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/packages/sdk/dist/node/index.mjs.map b/packages/sdk/dist/node/index.mjs.map index 2731ae767b..18bcfe5087 100644 --- a/packages/sdk/dist/node/index.mjs.map +++ b/packages/sdk/dist/node/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","ByteBuffer","_ByteBuffer","capacity","littleEndian","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","expiration","props","refBlockPrefix","expirationIso","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","count","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"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MAAA,CAAQ,MAAA,CACR,OAAA,CAAAJ,CACF,CAAC,CACH,CACF,CACF,CACF,CAAA,CACA,MAAA,CACArwC,CAAAA,CACA,SAAA,CACA,CAAE,aAAA,CAAeI,CAAAA,EAAiB,OAAQ,CAC5C,CACF","file":"index.mjs","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/hive-tx/helpers/ByteBuffer.ts","../../src/hive-tx/config.ts","../../src/hive-tx/helpers/Signature.ts","../../src/hive-tx/helpers/PublicKey.ts","../../src/hive-tx/helpers/Asset.ts","../../src/hive-tx/helpers/HexBuffer.ts","../../src/hive-tx/helpers/serializer.ts","../../src/hive-tx/helpers/sleep.ts","../../src/hive-tx/helpers/call.ts","../../src/hive-tx/Transaction.ts","../../src/hive-tx/helpers/PrivateKey.ts","../../src/hive-tx/helpers/aes.ts","../../src/hive-tx/helpers/deserializer.ts","../../src/hive-tx/helpers/memo.ts","../../src/hive-tx/helpers/utils.ts","../../src/modules/core/hive-tx.ts","../../src/modules/core/errors/chain-errors.ts","../../src/modules/core/mutations/use-broadcast-mutation.ts","../../src/modules/core/mutations/broadcast-json.ts","../../src/modules/core/mutations/invalidate-after-broadcast.ts","../../src/modules/core/abort-signal.ts","../../src/modules/core/config.ts","../../src/modules/core/queries-manager.ts","../../src/modules/core/utils/decoder-encoder.ts","../../src/modules/core/utils/parse-asset.ts","../../src/modules/core/utils/get-bound-fetch.ts","../../src/modules/core/utils/is-community.ts","../../src/modules/core/utils/pagination-helpers.ts","../../src/modules/core/utils/vests-to-hp.ts","../../src/modules/core/utils/is-empty-date.ts","../../src/modules/core/queries/get-dynamic-props-query-options.ts","../../src/modules/core/queries/get-reward-fund-query-options.ts","../../src/modules/core/query-keys.ts","../../src/modules/core/utf8.ts","../../src/modules/ai/queries/get-ai-generate-price-query-options.ts","../../src/modules/ai/queries/get-ai-assist-price-query-options.ts","../../src/modules/ai/queries/get-ai-transcribe-price-query-options.ts","../../src/modules/ai/mutations/use-generate-image.ts","../../src/modules/ai/mutations/use-ai-assist.ts","../../src/modules/ai/mutations/use-ai-transcribe.ts","../../src/modules/accounts/queries/get-account-full-query-options.ts","../../src/modules/accounts/utils/profile-metadata.ts","../../src/modules/accounts/utils/parse-accounts.ts","../../src/modules/accounts/utils/account-name-query.ts","../../src/modules/accounts/queries/get-accounts-query-options.ts","../../src/modules/accounts/queries/get-follow-count-query-options.ts","../../src/modules/accounts/queries/get-followers-query-options.ts","../../src/modules/accounts/queries/get-following-query-options.ts","../../src/modules/accounts/queries/get-muted-users-query-options.ts","../../src/modules/accounts/queries/lookup-accounts-query-options.ts","../../src/modules/accounts/queries/search-accounts-by-username-query-options.ts","../../src/modules/accounts/queries/check-username-wallets-pending-query-options.ts","../../src/modules/accounts/queries/get-relationship-between-accounts-query-options.ts","../../src/modules/accounts/queries/get-account-subscriptions-query-options.ts","../../src/modules/accounts/queries/get-bookmarks-query-options.ts","../../src/modules/accounts/queries/get-favorites-query-options.ts","../../src/modules/accounts/queries/check-favorite-query-options.ts","../../src/modules/accounts/queries/get-account-recoveries-query-options.ts","../../src/modules/accounts/queries/get-account-pending-recovery-query-options.ts","../../src/modules/accounts/queries/get-account-reputations-query-options.ts","../../src/modules/accounts/queries/get-transactions-infinite-query-options.ts","../../src/modules/accounts/queries/get-bots-query-options.ts","../../src/modules/accounts/queries/get-referrals-infinite-query-options.ts","../../src/modules/accounts/queries/get-referrals-stats-query-options.ts","../../src/modules/accounts/queries/get-friends-infinite-query-options.ts","../../src/modules/accounts/queries/get-search-friends-query-options.ts","../../src/modules/posts/queries/get-trending-tags-query-options.ts","../../src/modules/posts/queries/get-trending-tags-with-stats-query-options.ts","../../src/modules/posts/queries/get-fragments-query-options.ts","../../src/modules/posts/queries/get-promoted-posts-query-options.ts","../../src/modules/posts/queries/get-entry-active-votes-query-options.ts","../../src/modules/posts/queries/get-user-post-vote-query-options.ts","../../src/modules/posts/queries/get-content-query-options.ts","../../src/modules/posts/queries/get-content-replies-query-options.ts","../../src/modules/posts/queries/get-post-header-query-options.ts","../../src/modules/posts/utils/filter-dmca-entries.ts","../../src/modules/bridge/verify-on-alternate-node.ts","../../src/modules/posts/queries/get-post-query-options.ts","../../src/modules/bridge/requests.ts","../../src/modules/posts/queries/get-discussions-query-options.ts","../../src/modules/posts/queries/get-account-posts-query-options.ts","../../src/modules/posts/queries/get-posts-ranked-query-options.ts","../../src/modules/posts/queries/get-reblogs-query-options.ts","../../src/modules/posts/queries/get-reblogged-by-query-options.ts","../../src/modules/posts/queries/get-schedules-query-options.ts","../../src/modules/posts/queries/get-drafts-query-options.ts","../../src/modules/posts/queries/get-images-query-options.ts","../../src/modules/posts/queries/get-comment-history-query-options.ts","../../src/modules/posts/queries/get-deleted-entry-query-options.ts","../../src/modules/posts/queries/get-post-tips-query-options.ts","../../src/modules/posts/utils/waves-helpers.ts","../../src/modules/posts/queries/get-waves-feed-query-options.ts","../../src/modules/posts/queries/get-shorts-feed-query-options.ts","../../src/modules/posts/queries/get-waves-by-host-query-options.ts","../../src/modules/posts/queries/get-waves-by-tag-query-options.ts","../../src/modules/posts/queries/get-waves-following-query-options.ts","../../src/modules/posts/queries/get-waves-trending-tags-query-options.ts","../../src/modules/posts/queries/get-waves-by-account-query-options.ts","../../src/modules/posts/queries/get-waves-trending-authors-query-options.ts","../../src/modules/posts/queries/get-normalize-post-query-options.ts","../../src/modules/accounts/queries/get-account-vote-history-infinite-query-options.ts","../../src/modules/accounts/queries/get-profiles-query-options.ts","../../src/modules/accounts/queries/get-balance-history-query-options.ts","../../src/modules/accounts/queries/get-aggregated-balance-query-options.ts","../../src/modules/accounts/queries/get-pro-members-query-options.ts","../../src/modules/accounts/mutations/use-account-update.ts","../../src/modules/accounts/mutations/use-account-relations-update.ts","../../src/modules/operations/builders/content.ts","../../src/modules/operations/builders/wallet.ts","../../src/modules/operations/builders/social.ts","../../src/modules/operations/builders/governance.ts","../../src/modules/operations/builders/community.ts","../../src/modules/operations/builders/market.ts","../../src/modules/operations/builders/account.ts","../../src/modules/operations/builders/ecency.ts","../../src/modules/accounts/mutations/use-follow.ts","../../src/modules/accounts/mutations/use-unfollow.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-add.ts","../../src/modules/accounts/mutations/bookmarks/use-account-bookmark-delete.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-add.ts","../../src/modules/accounts/mutations/favorites/use-account-favorite-delete.ts","../../src/modules/accounts/mutations/use-account-update-key-auths.ts","../../src/modules/accounts/mutations/use-account-update-password.ts","../../src/modules/accounts/mutations/use-account-revoke-posting.ts","../../src/modules/accounts/mutations/use-account-update-recovery.ts","../../src/modules/accounts/mutations/build-revoke-keys-op.ts","../../src/modules/accounts/mutations/use-account-revoke-key.ts","../../src/modules/accounts/mutations/use-claim-account.ts","../../src/modules/accounts/mutations/use-grant-posting-permission.ts","../../src/modules/accounts/mutations/use-create-account.ts","../../src/modules/accounts/utils/account-power.ts","../../src/modules/operations/authority-map.ts","../../src/modules/operations/mutations/sign-operation-by-key.ts","../../src/modules/operations/mutations/sign-operation-by-keychain.ts","../../src/modules/operations/mutations/sign-operation-by-hivesigner.ts","../../src/modules/operations/queries/get-chain-properties-query-options.ts","../../src/modules/posts/utils/fragment-cache-helpers.ts","../../src/modules/posts/mutations/add-fragment.ts","../../src/modules/posts/mutations/edit-fragment.ts","../../src/modules/posts/mutations/remove-fragment.ts","../../src/modules/private-api/requests.ts","../../src/modules/posts/mutations/use-add-draft.ts","../../src/modules/posts/mutations/use-update-draft.ts","../../src/modules/posts/mutations/use-delete-draft.ts","../../src/modules/posts/mutations/use-add-schedule.ts","../../src/modules/posts/mutations/use-delete-schedule.ts","../../src/modules/posts/mutations/use-move-schedule.ts","../../src/modules/posts/mutations/use-add-image.ts","../../src/modules/posts/mutations/use-delete-image.ts","../../src/modules/posts/mutations/use-upload-image.ts","../../src/modules/posts/cache/entries-cache-management.ts","../../src/modules/posts/mutations/use-vote.ts","../../src/modules/posts/mutations/use-reblog.ts","../../src/modules/posts/mutations/use-comment.ts","../../src/modules/posts/cache/discussions-cache-utils.ts","../../src/modules/posts/mutations/use-delete-comment.ts","../../src/modules/posts/mutations/use-cross-post.ts","../../src/modules/posts/mutations/use-update-reply.ts","../../src/modules/posts/mutations/use-promote.ts","../../src/modules/posts/utils/validate-post-creating.ts","../../src/modules/analytics/mutations/index.ts","../../src/modules/analytics/mutations/use-record-activity.ts","../../src/modules/analytics/queries/get-discover-leaderboard-query-options.ts","../../src/modules/analytics/queries/get-discover-curation-query-options.ts","../../src/modules/analytics/queries/get-page-stats-query-options.ts","../../src/modules/integrations/3speak/functions/beneficiary.ts","../../src/modules/integrations/3speak/queries/index.ts","../../src/modules/integrations/hivesigner/queries/index.ts","../../src/modules/integrations/hivesigner/queries/get-decode-memo-query-options.ts","../../src/modules/integrations/hivesigner/index.ts","../../src/modules/integrations/3speak/queries/get-account-token-query-options.ts","../../src/modules/integrations/3speak/queries/get-account-videos-query-options.ts","../../src/modules/integrations/3speak/index.ts","../../src/modules/integrations/hiveposh/queries/get-hiveposh-links-query-options.ts","../../src/modules/integrations/plausible/queries/get-stats-query-options.ts","../../src/modules/resource-credits/queries/get-rc-stats-query-options.ts","../../src/modules/resource-credits/queries/get-account-rc-query-options.ts","../../src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts","../../src/modules/resource-credits/types/resource-params.ts","../../src/modules/resource-credits/utils/estimate-rc-precheck.ts","../../src/modules/resource-credits/utils/estimate-comment-rc-cost.ts","../../src/modules/games/queries/game-status-check-query-options.ts","../../src/modules/games/mutations/game-claim.ts","../../src/modules/quests/queries/get-quests-query-options.ts","../../src/modules/quests/catalog.ts","../../src/modules/quests/mutations/buy-streak-freeze.ts","../../src/modules/communities/mutations/use-subscribe-community.ts","../../src/modules/communities/mutations/use-unsubscribe-community.ts","../../src/modules/communities/mutations/use-mute-post.ts","../../src/modules/communities/mutations/use-set-community-role.ts","../../src/modules/communities/mutations/use-update-community.ts","../../src/modules/communities/mutations/use-register-community-rewards.ts","../../src/modules/communities/mutations/use-pin-post.ts","../../src/modules/communities/queries/get-communities-query-options.ts","../../src/modules/communities/queries/get-community-context-query-options.ts","../../src/modules/communities/queries/get-community-query-options.ts","../../src/modules/communities/queries/get-community-subscribers-query-options.ts","../../src/modules/communities/queries/get-account-notifications-infinite-query-options.ts","../../src/modules/communities/queries/get-rewarded-communities-query-options.ts","../../src/modules/communities/types/community.ts","../../src/modules/communities/utils/index.ts","../../src/modules/notifications/queries/get-notifications-unread-count-query-options.ts","../../src/modules/notifications/queries/get-notifications-infinite-query-options.ts","../../src/modules/notifications/enums/notification-filter.ts","../../src/modules/notifications/enums/notify-types.ts","../../src/modules/notifications/queries/get-notifications-settings-query-options.ts","../../src/modules/notifications/queries/get-announcements-query-options.ts","../../src/modules/notifications/queries/get-spotlights-query-options.ts","../../src/modules/notifications/mutations/use-mark-notifications-read.ts","../../src/modules/notifications/mutations/use-set-last-read.ts","../../src/modules/proposals/queries/get-proposal-query-options.ts","../../src/modules/proposals/queries/get-proposals-query-options.ts","../../src/modules/proposals/queries/get-proposal-votes-query-options.ts","../../src/modules/proposals/queries/get-user-proposal-votes-query-options.ts","../../src/modules/proposals/mutations/use-proposal-vote.ts","../../src/modules/proposals/mutations/use-proposal-create.ts","../../src/modules/wallet/queries/get-vesting-delegations-query-options.ts","../../src/modules/wallet/queries/get-account-delegations-query-options.ts","../../src/modules/wallet/queries/get-vesting-delegation-expirations-query-options.ts","../../src/modules/wallet/queries/get-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-collateralized-conversion-requests-query-options.ts","../../src/modules/wallet/queries/get-savings-withdraw-from-query-options.ts","../../src/modules/wallet/queries/get-withdraw-routes-query-options.ts","../../src/modules/wallet/queries/get-open-orders-query-options.ts","../../src/modules/wallet/queries/get-outgoing-rc-delegations-infinite-query-options.ts","../../src/modules/wallet/queries/get-incoming-rc-query-options.ts","../../src/modules/wallet/queries/get-received-vesting-shares-query-options.ts","../../src/modules/wallet/queries/get-recurrent-transfers-query-options.ts","../../src/modules/wallet/queries/get-portfolio-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-general-info-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-general-info-query-options.ts","../../src/modules/wallet/consts/hive-account-operation-groups.ts","../../src/modules/wallet/consts/hive-operation-list.ts","../../src/modules/wallet/consts/hive-operation-orders.ts","../../src/modules/wallet/queries/get-hive-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hbd-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-power-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-metric-query-options.ts","../../src/modules/wallet/queries/get-hive-asset-withdrawal-routes-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegates-query-options.ts","../../src/modules/wallet/queries/get-hive-power-delegatings-query-options.ts","../../src/modules/market/queries/get-order-book-query-options.ts","../../src/modules/market/queries/get-market-statistics-query-options.ts","../../src/modules/market/queries/get-market-history-query-options.ts","../../src/modules/market/queries/get-hive-hbd-stats-query-options.ts","../../src/modules/market/queries/get-market-data-query-options.ts","../../src/modules/market/queries/get-trade-history-query-options.ts","../../src/modules/market/queries/get-feed-history-query-options.ts","../../src/modules/market/queries/get-current-median-history-price-query-options.ts","../../src/modules/market/mutations/use-limit-order-create.ts","../../src/modules/market/mutations/use-limit-order-cancel.ts","../../src/modules/market/requests.ts","../../src/modules/hive-engine/requests.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-balances-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-market-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-tokens-metadata-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-transactions-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-metrics-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-unclaimed-rewards-query-options.ts","../../src/modules/hive-engine/queries/get-all-hive-engine-tokens-query-options.ts","../../src/modules/hive-engine/utils/formatted-number.ts","../../src/modules/hive-engine/utils/hive-engine-token.ts","../../src/modules/hive-engine/queries/get-hive-engine-balances-with-usd-query-options.ts","../../src/modules/hive-engine/queries/get-hive-engine-token-general-info-query-options.ts","../../src/modules/points/queries/get-points-query-options.ts","../../src/modules/points/queries/get-points-asset-general-info-query-options.ts","../../src/modules/points/queries/get-points-asset-transactions-query-options.ts","../../src/modules/wallet/queries/get-account-wallet-asset-info-query-options.ts","../../src/modules/wallet/types/asset-operation.ts","../../src/modules/wallet/mutations/use-transfer.ts","../../src/modules/wallet/mutations/use-transfer-point.ts","../../src/modules/wallet/mutations/use-delegate-vesting-shares.ts","../../src/modules/wallet/mutations/use-set-withdraw-vesting-route.ts","../../src/modules/wallet/mutations/use-transfer-engine-token.ts","../../src/modules/wallet/mutations/use-transfer-to-savings.ts","../../src/modules/wallet/mutations/use-transfer-from-savings.ts","../../src/modules/wallet/mutations/use-transfer-to-vesting.ts","../../src/modules/wallet/mutations/use-withdraw-vesting.ts","../../src/modules/wallet/mutations/use-convert.ts","../../src/modules/wallet/mutations/use-claim-interest.ts","../../src/modules/wallet/mutations/use-claim-rewards.ts","../../src/modules/wallet/mutations/use-delegate-engine-token.ts","../../src/modules/wallet/mutations/use-undelegate-engine-token.ts","../../src/modules/wallet/mutations/use-stake-engine-token.ts","../../src/modules/wallet/mutations/use-unstake-engine-token.ts","../../src/modules/wallet/mutations/use-claim-engine-rewards.ts","../../src/modules/wallet/mutations/use-engine-market-order.ts","../../src/modules/wallet/mutations/use-wallet-operation.ts","../../src/modules/wallet/mutations/use-delegate-rc.ts","../../src/modules/witnesses/mutations/use-witness-vote.ts","../../src/modules/witnesses/mutations/use-witness-proxy.ts","../../src/modules/witnesses/queries/get-witnesses-query-options.ts","../../src/modules/points/types/point-transaction-type.ts","../../src/modules/points/mutations/use-claim-points.ts","../../src/modules/search/query-builder.ts","../../src/modules/search/parse-json-response.ts","../../src/modules/search/retry-policy.ts","../../src/modules/search/queries/get-search-query-options.ts","../../src/modules/search/requests.ts","../../src/modules/search/queries/get-similar-entries-query-options.ts","../../src/modules/search/queries/get-search-account-query-options.ts","../../src/modules/search/queries/get-search-topics-query-options.ts","../../src/modules/search/queries/get-search-api-infinite-query-options.ts","../../src/modules/search/queries/get-search-path-query-options.ts","../../src/modules/support/queries/get-support-settings-query-options.ts","../../src/modules/support/mutations/update-support-settings.ts","../../src/modules/promotions/queries/get-boost-plus-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-prices-query-options.ts","../../src/modules/promotions/queries/get-rc-delegation-active-query-options.ts","../../src/modules/promotions/queries/get-promote-price-query-options.ts","../../src/modules/promotions/queries/get-boost-plus-account-prices-query-options.ts","../../src/modules/promotions/mutations/use-boost-plus.ts","../../src/modules/promotions/mutations/use-rc-delegation.ts","../../src/modules/auth/requests.ts","../../src/modules/bad-actors/queries/get-bad-actors-query-options.ts","../../src/modules/polls/types/poll.ts","../../src/modules/polls/queries/get-poll-query-options.ts","../../src/modules/polls/mutations/use-poll-vote.ts"],"names":["EMPTY_BUFFER","_encoder","_decoder","getEncoder","s","utf8","i","c","next","getDecoder","b","bytes","result","byte","codePoint","ByteBuffer","_ByteBuffer","capacity","littleEndian","buffers","buf","bb","view","offset","buffer","source","value","relative","src","copy","begin","end","target","targetOffset","sourceOffset","sourceLimit","targetRelative","len","current","length","forceCopy","limit","size","str","currentOffset","encoded","lenVarintSize","start","lenResult","lenValue","lenLength","config","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","opts","r","bool","v","pos","Signature","_Signature","data","recovery","compressed","string","temp","hexToBytes","bytesToHex","message","sig","secp256k1","PublicKey","_PublicKey","key","prefix","wif","expectedPrefix","bs58","checksum","expectedChecksum","ripemd160","isUint8ArrayEqual","signature","encodePublic","a","Asset","_Asset","amount","symbol","expectedSymbol","amountString","HexBuffer","_HexBuffer","OPERATION_IDS","VoidSerializer","StringSerializer","Int16Serializer","Int64Serializer","UInt8Serializer","UInt16Serializer","UInt32Serializer","UInt64Serializer","BooleanSerializer","StaticVariantSerializer","itemSerializers","id","item","AssetSerializer","asset","precision","DateSerializer","PublicKeySerializer","BinarySerializer","VariableBinarySerializer","FlatMapSerializer","keySerializer","valueSerializer","ArraySerializer","itemSerializer","ObjectSerializer","keySerializers","serializer","error","OptionalSerializer","AuthoritySerializer","BeneficiarySerializer","PriceSerializer","ChainPropertiesSerializer","OperationDataSerializer","operationId","definitions","objectSerializer","OperationSerializers","ProposalUpdateSerializer","OperationSerializer","operation","TransactionSerializer","EncryptedMemoSerializer","Serializer","sleep","ms","resolve","isNodeRuntime","serverIdentityHeaders","RPCError","rpcError","NodeError","node","parseRetryAfterMs","header","secs","dateMs","delta","PRE_CONNECTION_ERRORS","BROWSER_NETWORK_ERRORS","flattenErrorText","parts","cause","depth","isBroadcastSafeToRetry","text","code","msg","isNodeLevelRPCError","apiOf","method","dot","RATE_LIMIT_BASE_MS","RATE_LIMIT_MAX_MS","RATE_LIMIT_STREAK_RESET_MS","MAX_API_FAILURES_BEFORE_COOLDOWN","API_COOLDOWN_MS","HEAD_BLOCK_MAX_AGE_MS","STALE_BLOCK_THRESHOLD","LATENCY_EWMA_ALPHA","LATENCY_MIN_SAMPLES","LATENCY_MAX_AGE_MS","LATENCY_REPROBE_MS","LATENCY_UNPROVEN_PRIOR_MS","LATENCY_SLOW_FAILURE_MS","NodeHealthTracker","h","durationMs","profileKey","apiFail","now","p","elapsedMs","existing","retryAfterMs","hasHeader","cooldown","blockNum","recent","best","healthy","unhealthy","ordered","d","probe","threshold","cand","candTouch","touch","rpcHealthTracker","restHealthTracker","HedgeBudget","tokens","rpcHedgeBudget","adaptiveAttemptTimeout","tracker","callerTimeout","explicit","ewma","recordError","e","tryRecordHeadBlock","block","createTimeoutReason","err","createTimeoutSignal","controller","timer","mergeSignals","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","url","params","timeout","shouldRetry","externalSignal","body","tSignal","cleanupTimeout","signal","cleanupMerge","res","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","validate","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","deadline","triedInRound","attempt","orderedNodes","callStart","callRPCBroadcast","triedNodes","apiMethods","callREST","endpoint","restProfileKey","apiNodes","alreadyRecorded","baseUrl","path","paramObj","processedPathParams","restSignal","restCleanup","restCallStart","response","callWithQuorum","quorum","allNodes","arr","j","currentBatchSize","allResults","batchNodes","promises","batchResults","consensusResult","findConsensus","results","resultGroups","consensusGroup","group","chainId","Transaction","_Transaction","options","operationName","operationBody","keys","digest","txId","checkStatus","maxPollAttempts","status","transactionData","sha256","expiration","props","refBlockPrefix","expirationIso","NETWORK_ID","PrivateKey","_PrivateKey","decodePrivate","seed","username","password","role","rv","encodePrivate","publicKey","sha512","doubleSha256","input","encodedKey","checksumVerify","encrypt","privateKey","nonce","uniqueNonce","crypt","decrypt","nonceL","S","ebuf","encryptionKey","iv","tag","check","cbuf","check32","cryptoJsDecrypt","cryptoJsEncrypt","messageBuffer","AESCBC","uniqueNonceEntropy","randomPrivateKey","long","entropy","PublicKeyDeserializer","fixedBuf","UInt64Deserializer","UInt32Deserializer","BinaryDeserializer","bCopy","BufferDeserializer","keyDeserializers","obj","deserializer","EncryptedMemoDeserializer","Deserializer","encode","memo","testNonce","checkEncryption","toPrivateObj","toPublicObj","mbuf","memoBuffer","mbuf2","decode","from","to","encrypted","otherpub","encodeTest","plaintext","cyphertext","o","Memo","utils_exports","__export","buildWitnessSetProperties","makeBitMaskFilter","operations","validateUsername","suffix","ref","label","allowedOperations","reduceFunction","low","high","allowedOperation","owner","type","serialize","nobleSha256","isWif","broadcastOperations","ops","tx","op","broadcastOperationsAsync","MANA_REGENERATION_SECONDS","calculateManabar","maxMana","manabar","currentMana","percentage","getVests","account","vests","delegated","received","withdrawRate","alreadyWithdrawn","withdrawVests","calculateVPMana","calculateRCMana","rcAccount","ErrorType","parseChainError","errorDescription","errorMessage","errorCode","errorString","testPattern","pattern","formatError","parsed","shouldTriggerAuthFallback","isResourceCreditsError","isInfoError","isNetworkError","broadcastWithMethod","auth","authority","fetchedKey","fetchedToken","broadcastMode","adapter","token","hs","tokenError","broadcastWithFallback","loginType","hasPostingAuth","selectedMethod","hsError","chain","errors","shouldSkip","skipReason","prefetchedKey","prefetchedToken","skipReasons","errorMessages","useBroadcastMutation","mutationKey","onSuccess","useMutation","payload","postingKey","accessToken","broadcastJson","jjson","BROADCAST_INCLUSION_DELAY_MS","invalidateAfterBroadcast","withTimeoutSignal","timeoutMs","timeoutSignal","ac","onAbort","reason","isDevelopment","getHeliusApiKey","INTERNAL_API_TIMEOUT_MS","SERVER_GC_TIME_MS","queryClientResolver","fallbackQueryClient","resolveQueryClient","QueryClient","CONFIG","client","ConfigManager","setQueryClient","setQueryClientResolver","setPrivateApiHost","host","setClientId","clientId","setDefaultObserver","observer","getValidatedBaseUrl","setPollsApiHost","setImageHost","setHiveNodes","userAgent","analyzeRedosRisk","unboundedRange","match","min","max","testRegexPerformance","regex","adversarialInputs","maxExecutionTime","duration","safeCompileRegex","maxLength","staticAnalysis","compileErr","runtimeTest","setDmcaLists","lists","coerceList","resolved","rejectedTagCount","makeQueryClient","getQueryClient","EcencyQueriesManager","getQueryData","queryKey","getInfiniteQueryData","prefetchQuery","prefetchInfiniteQuery","generateClientServerQuery","useQuery","generateClientServerInfiniteQuery","useInfiniteQuery","encodeObj","decodeObj","dataToParse","Symbol","NaiMap","parseAsset","sval","sp","cachedFetch","getBoundFetch","isCommunity","isWrappedResponse","normalizeToWrappedResponse","vestsToHp","hivePerMVests","isEmptyDate","DYNAMIC_PROPS_REFRESH_MS","getDynamicPropsQueryOptions","queryOptions","QueryKeys","rawGlobalDynamic","rawFeedHistory","rawChainProps","rawRewardFund","rawHardforkProps","totalVestingSharesAmount","totalVestingFundAmount","base","quote","fundRecentClaims","fundRewardBalance","votePowerReserveRate","authorRewardCurve","contentConstant","currentHardforkVersion","lastHardfork","hbdPrintRate","hbdInterestRate","headBlock","totalVestingFund","totalVestingShares","virtualSupply","vestingRewardPercent","accountCreationFee","getRewardFundQueryOptions","fundName","entryPath","author","permlink","filter","startAuthor","startPermlink","activeUsername","sort","order","onlyMeta","hours","usernames","following","mode","followType","query","follower","startFollowing","startFollower","excludeList","accounts","targetUsername","reference","name","communityName","proposalId","voter","q","hideLow","since","scrollId","votes","what","content","includeNsfw","witness","page","pageSize","direction","user","coinType","granularity","onlyEnabled","currency","filterKey","bucketSeconds","seconds","startDate","endDate","coin","vsCurrency","fromTs","toTs","dimensions","metrics","dateRange","gameType","utf8ByteLength","varintByteLength","count","remaining","getAiGeneratePriceQueryOptions","getAiAssistPriceQueryOptions","getAiTranscribePriceQueryOptions","makeIdempotencyKey","useGenerateImage","pendingData","useAiAssist","useAiTranscribe","form","isMetadataStripped","hasProfileValues","profile","getAccountFullQueryOptions","bridgeProfile","rows","chainAccount","reread","parseProfileMetadata","stats","follow_stats","reputationValue","DENIED_KEYS","isPlainObject","proto","deepMerge","srcVal","tgtVal","sanitizeTokens","meta","rest","safeMeta","postingJsonMetadata","extractAccountProfile","pickRicherMetadataSnapshot","preferred","fallback","preferredKeys","parsePostingMetadataRoot","buildPostingJsonMetadata","existingPostingJsonMetadata","root","existingProfile","mergedProfile","buildProfileMetadata","profileTokens","_ignoredVersion","profileRest","metadata","parseAccounts","rawAccounts","x","jsonMetadata","accountNameByteLength","isQueryableAccountName","getAccountsQueryOptions","queryable","getFollowCountQueryOptions","getFollowersQueryOptions","getFollowingQueryOptions","MUTED_USERS_PAGE_SIZE","MUTED_USERS_MAX_PAGES","getMutedUsersQueryOptions","muted","names","lookupAccountsQueryOptions","getSearchAccountsByUsernameQueryOptions","RESERVED_META_KEYS","checkUsernameWalletsPendingQueryOptions","wallets","walletItem","sanitizedMeta","address","showFlag","baseCandidate","metaTokenCandidates","metaSymbol","metaValue","getRelationshipBetweenAccountsQueryOptions","getAccountSubscriptionsQueryOptions","getBookmarksQueryOptions","getBookmarksInfiniteQueryOptions","infiniteQueryOptions","pageParam","json","lastPage","getFavoritesQueryOptions","getFavoritesInfiniteQueryOptions","checkFavoriteQueryOptions","getAccountRecoveriesQueryOptions","getAccountPendingRecoveryQueryOptions","getAccountReputationsQueryOptions","ACCOUNT_OPERATION_GROUPS","ALL_ACCOUNT_OPERATIONS","deriveNum","entry","normalizeOpType","restType","isNaiAsset","naiToString","normalizeOpValue","k","getTransactionsInfiniteQueryOptions","operationTypes","fetchPage","toEntries","entries","currentPage","chained","nextPage","getBotsQueryOptions","getReferralsInfiniteQueryOptions","maxId","nextMaxId","getReferralsStatsQueryOptions","getFriendsInfiniteQueryOptions","enabled","accountNames","SEARCH_LIMIT","getSearchFriendsQueryOptions","getTrendingTagsQueryOptions","afterTag","tags","getTrendingTagsWithStatsQueryOptions","getFragmentsQueryOptions","getFragmentsInfiniteQueryOptions","getPromotedPostsQuery","getEntryActiveVotesQueryOptions","getUserPostVoteQueryOptions","getContentQueryOptions","getContentRepliesQueryOptions","getPostHeaderQueryOptions","filterDmcaEntry","entryOrEntries","applyFilter","verifyPostOnAlternateNode","getPostQueryOptions","num","cleanPermlink","verified","verifiedEntry","bridgeApiCall","resolvePost","post","resp","getPost","resolvePosts","posts","validatedPosts","validateEntry","getPostsRanked","start_author","start_permlink","getAccountPosts","newEntry","requiredStringProps","prop","validatedEntry","getPostHeader","getDiscussion","validatedResp","getCommunity","getCommunities","last","normalizePost","getSubscriptions","getSubscribers","community","getRelationshipBetweenAccounts","getProfiles","SortOrder","sortDiscussions","discussion","allPayout","absNegative","isPinned","sortOrders","_a","_b","keyA","keyB","sorted","pinnedIndex","pinned","getDiscussionsQueryOptions","resolvedObserver","oldData","newData","optimisticEntries","fetchedPermlinks","missingOptimistic","opt","getDiscussionQueryOptions","getAccountPostsInfiniteQueryOptions","hasNextPage","getAccountPostsQueryOptions","displaySelects","displaySelect","select","orderForDisplay","byCreated","getPostsRankedInfiniteQueryOptions","_options","sanitizedTag","getPostsRankedQueryOptions","getReblogsQueryOptions","getRebloggedByQueryOptions","getSchedulesQueryOptions","getSchedulesInfiniteQueryOptions","getDraftsQueryOptions","getDraftsInfiniteQueryOptions","fetchUserImages","getImagesQueryOptions","getGalleryImagesQueryOptions","getImagesInfiniteQueryOptions","getCommentHistoryQueryOptions","makeEntryPath","cleanAuthor","normalizedAuthor","normalizedPermlink","getDeletedEntryQueryOptions","isValid","history","title","getPostTipsQueryOptions","isEnabled","normalizeContainer","normalizeParent","normalizeWaveEntryFromApi","containerSource","container","parent","toEntryArray","getVisibleFirstLevelThreadItems","discussionItemsRaw","discussionItems","firstLevelItems","parent_author","parent_permlink","mapThreadItemsToWaveEntries","items","DEFAULT_FEED_LIMIT","normalizeParams","fetchWavesFeedPage","containers","cursor","row","getWavesFeedQueryOptions","normalized","getWavesLatestFeedQueryOptions","fetchShortsFeedPage","getShortsFeedQueryOptions","THREAD_CONTAINER_BATCH_SIZE","MAX_CONTAINERS_TO_SCAN","getThreads","scannedContainers","skipContainerId","rpcParams","normalizedContainers","visibleItems","lastContainer","getWavesByHostQueryOptions","DEFAULT_TAG_FEED_LIMIT","getWavesByTagQueryOptions","getWavesFollowingQueryOptions","normalizedUsername","flattened","getWavesTrendingTagsQueryOptions","getWavesByAccountQueryOptions","getWavesTrendingAuthorsQueryOptions","getNormalizePostQueryOptions","isEntry","getDays","createdDate","past","getAccountVoteHistoryInfiniteQueryOptions","filters","dayLimit","historyObj","filtered","firstHistory","getProfilesQueryOptions","getBalanceHistoryInfiniteQueryOptions","getAggregatedBalanceQueryOptions","getProMembersQueryOptions","proMembersSet","members","m","useAccountUpdate","queryClient","useQueryClient","_data","variables","useAccountRelationsUpdate","onError","kind","relationsQuery","actualRelation","buildVoteOp","weight","buildCommentOp","parentAuthor","parentPermlink","buildCommentOptionsOp","maxAcceptedPayout","percentHbd","allowVotes","allowCurationRewards","extensions","buildDeleteCommentOp","buildReblogOp","deleteReblog","buildTransferOp","buildMultiTransferOps","destinations","dest","buildRecurrentTransferOp","recurrence","executions","buildTransferToSavingsOp","buildTransferFromSavingsOp","requestId","buildCancelTransferFromSavingsOp","buildClaimInterestOps","buildTransferToVestingOp","buildWithdrawVestingOp","vestingShares","buildDelegateVestingSharesOp","delegator","delegatee","buildSetWithdrawVestingRouteOp","fromAccount","toAccount","percent","autoVest","buildConvertOp","buildCollateralizedConvertOp","buildEngineOp","contractAction","contractPayload","contractName","buildEngineClaimOp","buildDelegateRcOp","delegatees","maxRc","delegateeArray","buildFollowOp","buildUnfollowOp","buildIgnoreOp","buildUnignoreOp","buildSetLastReadOps","date","lastReadDate","notifyOp","ecencyNotifyOp","buildWitnessVoteOp","approve","buildWitnessProxyOp","proxy","buildProposalCreateOp","creator","buildProposalVoteOp","proposalIds","buildRemoveProposalOp","proposalOwner","buildUpdateProposalOp","dailyPay","subject","buildSubscribeOp","buildUnsubscribeOp","buildSetRoleOp","buildUpdateCommunityOp","buildPinPostOp","pin","buildMutePostOp","notes","mute","buildMuteUserOp","buildFlagPostOp","BuySellTransactionType","OrderIdPrefix","buildLimitOrderCreateOp","amountToSell","minToReceive","fillOrKill","orderId","formatNumber","decimals","buildLimitOrderCreateOpWithType","orderType","idPrefix","expirationStr","formattedAmountToSell","formattedMinToReceive","buildLimitOrderCancelOp","buildClaimRewardBalanceOp","rewardHive","rewardHbd","rewardVests","buildAccountUpdateOp","active","posting","memoKey","buildAccountUpdate2Op","buildAccountCreateOp","newAccountName","fee","buildCreateClaimedAccountOp","buildClaimAccountOp","buildGrantPostingPermissionOp","currentPosting","grantedAccount","weightThreshold","existingIndex","acc","newAccountAuths","newPosting","buildRevokePostingPermissionOp","revokedAccount","buildChangeRecoveryAccountOp","accountToRecover","newRecoveryAccount","buildRequestAccountRecoveryOp","recoveryAccount","newOwnerAuthority","buildRecoverAccountOp","recentOwnerAuthority","buildBoostPlusOp","buildRcDelegationOp","buildPromoteOp","buildPointTransferOp","sender","receiver","normalizedAmount","buildMultiPointTransferOps","destArray","buildCommunityRegistrationOp","buildActiveCustomJsonOp","buildPostingCustomJsonOp","useFollow","_result","useUnfollow","useBookmarkAdd","useBookmarkDelete","bookmarkId","useAccountFavoriteAdd","qc","useAccountFavoriteDelete","listKey","infinitePrefix","checkKey","previousList","f","previousCheck","infiniteQueries","previousInfinite","context","dedupeAndSortKeyAuths","additions","useAccountUpdateKeyAuths","accountData","keepCurrent","currentKey","keysToRevoke","keysToRevokeByAuthority","prepareAuth","keyName","allKeysToRevoke","existingKeys","values","useAccountUpdatePassword","updateKeys","newPassword","currentPassword","useAccountRevokePosting","accountName","ctx","useAccountUpdateRecovery","email","canRevokeFromAuthority","revokingKeyStrs","remainingWeight","sum","accountWeight","buildRevokeKeysOp","revokingKeys","hasAnyKeyInAuth","clone","needsOwnerUpdate","useAccountRevokeKey","revokingKey","useClaimAccount","useGrantPostingPermission","useCreateAccount","HIVE_VOTING_MANA_REGENERATION_SECONDS","HIVE_100_PERCENT","HIVE_VOTE_DUST_THRESHOLD","getEffectiveVests","vesting","vestsToRshares","votingPowerValue","votePerc","hasStableVoteHardfork","dynamicProps","major","minor","stableVoteRshares","reserveRate","effectiveVests","usedMana","mana","votingRshares","totalVests","votingPower","powerRechargeTime","power","downVotingPower","totalShares","elapsed","currentManaPerc","rcPower","votingValue","rShares","OPERATION_AUTHORITY_MAP","getCustomJsonAuthority","customJsonOp","opType","customJson","getProposalAuthority","proposalOp","getOperationAuthority","getRequiredAuthority","highestAuthority","useSignOperationByKey","keyOrSeed","useSignOperationByKeychain","keyType","useSignOperationByHivesigner","callbackUri","getChainPropertiesQueryOptions","applyFragmentUpdate","vars","buildAddedFragment","useAddFragment","newFragment","index","useEditFragment","fragmentId","applyUpdate","fragment","useRemoveFragment","parseJsonResponse","errorData","signUp","referral","captchaToken","subscribeEmail","usrActivity","ty","bl","getNotifications","saveNotificationSetting","system","allows_notify","notify_types","getNotificationSetting","markNotifications","addImage","UPLOAD_HOST","uploadImage","file","fetchApi","formData","uploadImageWithSignature","deleteImage","imageId","addDraft","updateDraft","draftId","deleteDraft","addSchedule","schedule","reblog","deleteSchedule","moveSchedule","getPromotedPost","onboardEmail","friend","dataBody","useAddDraft","useUpdateDraft","useDeleteDraft","_variables","useAddSchedule","useDeleteSchedule","useMoveSchedule","useAddImage","nextCode","effectiveCode","useDeleteImage","prev","img","useUploadImage","getEntryFromCache","setEntryInCache","mutateEntry","updater","updated","EntriesCacheManagement","updateVotes","payout","updateReblogsCount","updateRepliesCount","addReply","reply","updateEntries","invalidateEntry","getEntry","isVoteAlreadyReflected","activeVotes","hasVoterRecord","applyVoteCacheUpdate","newVotes","newPayout","useVote","doInvalidate","useReblog","newCount","invalidate","useComment","beneficiaries","sortedBeneficiaries","isPost","activityType","queriesToInvalidate","discussionsAuthor","discussionsPermlink","addOptimisticDiscussionEntry","rootAuthor","rootPermlink","queries","removeOptimisticDiscussionEntry","snapshots","restoreDiscussionSnapshots","updateEntryInCache","updates","previous","restoreEntryInCache","useDeleteComment","_error","useCrossPost","useUpdateReply","usePromote","DEFAULT_VALIDATE_POST_DELAYS","getContent","validatePostCreating","attempts","delays","waitMs","mutations_exports","useRecordActivity","getLocationInfo","locationInfo","domain","getDiscoverLeaderboardQueryOptions","getDiscoverCurationQueryOptions","accountsResponse","element","curator","receivedVestingShares","delegatedVestingShares","vestingWithdrawRate","effectiveVest","getPageStatsQueryOptions","sortedDimensions","sortedMetrics","THREESPEAK_BENEFICIARY_ACCOUNT","THREESPEAK_BENEFICIARY_WEIGHT","hasThreeSpeakEmbed","enforceThreeSpeakBeneficiary","isThreeSpeakBeneficiary","queries_exports","getAccountTokenQueryOptions","getAccountVideosQueryOptions","getDecodeMemoQueryOptions","HiveSignerIntegration","memoQueryOptions","memoDecoded","tokenQueryOptions","ThreeSpeakIntegration","getHivePoshLinksQueryOptions","getStatsQueryOptions","filterBy","getRcStatsQueryOptions","getAccountRcQueryOptions","getRcResourceParamsQueryOptions","RC_RESOURCE_NAMES","EMPTY","estimateRcPrecheck","rcStats","avgCost","safeBuffer","estimatedCost","willLikelyFail","TRANSACTION_HEADER_BYTES","SIGNATURE_BYTES","ASSET_BYTES","big","computeResourceCost","curve","pool","resourceCount","regenShare","coeffA","coeffB","shift","denom","countCommentResourceUsage","transactionBytes","permlinkLength","signatures","hasCommentOptions","sizeInfo","state","exec","stringFieldBytes","commentOperationBytes","commentOptionsBytes","route","estimateCommentTransactionBytes","estimateCommentRcCost","rcParams","usage","regen","cost","breakdown","share","scaled","resourceCost","getGameStatusCheckQueryOptions","useGameClaim","recordActivity","getQuestsQueryOptions","QUEST_CATALOG","getQuestCatalogEntry","tier","QUEST_MIN_CONTENT_LENGTH","measureQuestContentLength","earnsQuestContentCredit","STREAK_FREEZE_PRICE","STREAK_FREEZE_MAX_OWNED","genIdempotencyKey","buyStreakFreezeRequest","useBuyStreakFreeze","useSubscribeCommunity","useUnsubscribeCommunity","useMutePost","useSetCommunityRole","team","idx","useUpdateCommunity","useRegisterCommunityRewards","usePinPost","getCommunitiesQueryOptions","getCommunityContextQueryOptions","getCommunityQueryOptions","SUBSCRIBERS_PAGE_SIZE","fetchSubscribersPage","getCommunitySubscribersQueryOptions","getCommunitySubscribersInfiniteQueryOptions","getAccountNotificationsInfiniteQueryOptions","getRewardedCommunitiesQueryOptions","ROLES","roleMap","getCommunityType","type_id","getCommunityPermissions","communityType","userRole","subscribed","canPost","canComment","isModerator","getNotificationsUnreadCountQueryOptions","getNotificationsInfiniteQueryOptions","NotificationFilter","NotifyTypes","ALL_NOTIFY_TYPES","NotificationViewType","getNotificationsSettingsQueryOptions","initialMuted","getAnnouncementsQueryOptions","getSpotlightsQueryOptions","_accessToken","markNotificationRead","isInfiniteData","useMarkNotificationsRead","previousData","updatedData","unreadKey","currentUnread","unreadCount","useSetLastRead","getProposalQueryOptions","proposal","getProposalsQueryOptions","proposals","expired","getProposalVotesInfiniteQueryOptions","getUserProposalVotesQueryOptions","vote","useProposalVote","useProposalCreate","getVestingDelegationsQueryOptions","fetchLimit","getAccountDelegationsQueryOptions","getVestingDelegationExpirationsQueryOptions","getConversionRequestsQueryOptions","getCollateralizedConversionRequestsQueryOptions","getSavingsWithdrawFromQueryOptions","getWithdrawRoutesQueryOptions","getOpenOrdersQueryOptions","getOutgoingRcDelegationsInfiniteQueryOptions","delegations","delegation","getIncomingRcQueryOptions","getReceivedVestingSharesQueryOptions","getRecurrentTransfersQueryOptions","normalizeString","trimmed","normalizeNumber","direct","parseToken","rawToken","extractTokens","record","resolveUsername","getPortfolioQueryOptions","getHiveAssetGeneralInfoQueryOptions","marketTicker","marketPrice","liquidBalance","savingsBalance","getHbdAssetGeneralInfoQueryOptions","price","getAPR","currentInflationRate","totalVestingFunds","getHivePowerAssetGeneralInfoQueryOptions","delegatedVests","receivedVests","withdrawRateVests","remainingToWithdrawVests","nextWithdrawalVests","hpBalance","outgoingDelegationsHp","incomingDelegationsHp","pendingPowerDownHp","nextPowerDownHp","totalBalance","availableHp","HIVE_ACCOUNT_OPERATION_GROUPS","HIVE_OPERATION_LIST","operationOrders","HIVE_OPERATION_ORDERS","HIVE_OPERATION_NAME_BY_ID","isHiveOperationName","resolveHiveOperationFilters","rawValues","hasAll","uniqueValues","operationIds","filterArgs","collectRequestedOperations","getNextAccountHistoryPageParam","oldest","resolveAccountHistoryLimit","getHiveAssetTransactionsQueryOptions","requestedOperations","pages","pageParams","getHbdAssetTransactionsQueryOptions","getHivePowerAssetTransactionsQueryOptions","userSelectedOperations","hasAllFilter","formatDate","pad","subtractSeconds","getHiveAssetMetricQueryOptions","hive","non_hive","open","_","__","prevStartDate","getHiveAssetWithdrawalRoutesQueryOptions","getHivePowerDelegatesInfiniteQueryOptions","getHivePowerDelegatingsQueryOptions","getOrderBookQueryOptions","getMarketStatisticsQueryOptions","getMarketHistoryQueryOptions","getHiveHbdStatsQueryOptions","oneDayAgo","dayChange","getMarketDataQueryOptions","getTradeHistoryQueryOptions","getFeedHistoryQueryOptions","getCurrentMedianHistoryPriceQueryOptions","useLimitOrderCreate","useLimitOrderCancel","getMarketData","getCurrencyRate","cur","getCurrencyTokenRate","getCurrencyRates","getHivePrice","ENGINE_RPC_HEADERS","engineRpc","engineRpcSafe","getHiveEngineOrderBook","baseParams","buy","sell","sortByPriceDesc","left","sortByPriceAsc","right","getHiveEngineTradeHistory","getHiveEngineOpenOrders","buyRaw","sellRaw","formatTotal","quantity","getHiveEngineMetrics","symbolQuery","getHiveEngineTokensMarket","getHiveEngineTokensBalances","getHiveEngineTokensMetadata","getHiveEngineTokenTransactions","getHiveEngineTokenMetrics","interval","getHiveEngineUnclaimedRewards","getHiveEngineTokensBalancesQueryOptions","getHiveEngineTokensMarketQueryOptions","getHiveEngineTokensMetadataQueryOptions","getHiveEngineTokenTransactionsQueryOptions","_allPages","lastPageParam","_firstPage","firstPageParam","getHiveEngineTokensMetricsQueryOptions","getHiveEngineUnclaimedRewardsQueryOptions","pending_token","getAllHiveEngineTokensQueryOptions","formattedNumber","fractionDigits","out","av","HiveEngineToken","getHiveEngineBalancesWithUsdQueryOptions","allTokens","balances","t","pricePerHive","providedMetrics","unpricedSymbols","balance","metric","tokenMetadata","lastPrice","balanceAmount","usdValue","getHiveEngineTokenGeneralInfoQueryOptions","hiveQuery","hiveData","metadataList","balanceList","marketList","stakedBalance","unstakingBalance","getPointsQueryOptions","pointsResponse","points","transactionsResponse","transactions","getPointsAssetGeneralInfoQueryOptions","getPointsAssetTransactionsQueryOptions","created","getAccountWalletAssetInfoQueryOptions","fetchQuery","qo","convertPriceToUserCurrency","assetInfo","conversionRate","portfolioQuery","getPortfolioAssetInfo","assetItem","extraItem","dataKey","numValue","portfolioAssetInfo","converted","AssetOperation","useTransfer","useTransferPoint","useDelegateVestingShares","useSetWithdrawVestingRoute","useTransferEngineToken","useTransferToSavings","useTransferFromSavings","useTransferToVesting","useWithdrawVesting","useConvert","useClaimInterest","CLAIM_REWARDS_INVALIDATION_DELAY_MS","pendingInvalidationTimers","useClaimRewards","timerKey","keysToInvalidate","existingTimer","rejected","useDelegateEngineToken","useUndelegateEngineToken","useStakeEngineToken","useUnstakeEngineToken","useClaimEngineRewards","useEngineMarketOrder","buildHiveOperations","buildEngineOperations","getWalletOperationAuthority","useWalletOperation","hiveOps","engineOps","useDelegateRc","useWitnessVote","useWitnessProxy","mapRestWitness","w","getWitnessesInfiniteQueryOptions","getWitnessVotersPageQueryOptions","getWitnessVoterCountQueryOptions","PointTransactionType","claimPointsRequest","contentType","detail","useClaimPoints","author_re","type_re","category_re","tag_re","SearchType","MAX_SEARCH_TAGS","MAX_SEARCH_QUERY_LENGTH","firstToken","normalizeSearchAuthor","normalizeSearchCategory","normalizeSearchTags","seen","buildSearchQuery","search","category","normalizedSearch","normalizedCategory","normalizedTags","part","SearchQuery","_query","re","matches","raw","isSearchResponse","MAX_RETRIES","isServer","searchRetryPolicy","failureCount","isTransient","searchQueryOptions","scroll_id","getControversialRisingInfiniteQueryOptions","sinceDate","similar","searchPath","SIMILAR_ENTRIES_SINCE_MS","SIMILAR_ENTRIES_TARGET","SIMILAR_ENTRIES_BODY_LIMIT","SIMILAR_ENTRIES_SSR_TIMEOUT_MS","SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS","SIMILAR_ENTRIES_MIN_RENDER","toMltExcerpt","fingerprint","getSimilarEntriesQueryOptions","rawTags","contentKey","collected","seenAuthors","getSearchAccountQueryOptions","getSearchTopicsQueryOptions","getSearchApiInfiniteQueryOptions","getSearchPathQueryOptions","getSupportSettingsRequest","getSupportSettingsQueryOptions","updateSupportSettingsRequest","applySupportSettingsUpdate","useUpdateSupportSettings","getBoostPlusPricesQueryOptions","getRcDelegationPricesQueryOptions","getRcDelegationActiveQueryOptions","responseData","getPromotePriceQueryOptions","getBoostPlusAccountPricesQueryOptions","useBoostPlus","useRcDelegation","hsTokenRenew","BAD_ACTORS_URL","getBadActorsQueryOptions","POLLS_PROTOCOL_VERSION","PollPreferredInterpretation","mapMetaChoicesToPollChoices","metaChoices","choice","normalizePoll","pollChoices","pollVoters","rawStats","choices","voters","getPollQueryOptions","usePollVote","pollTrxId"],"mappings":"whBASA,IAAMA,EAAAA,CAAe,IAAI,YAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,EAAAA,EAAgD,CACvD,OAAKF,EAAAA,GACC,OAAO,YAAgB,GAAA,CACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,OAAOG,CAAAA,CAAuB,CAE5B,IAAMC,CAAAA,CAAiB,GACvB,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,IAAK,CACjC,IAAIC,EAAIH,CAAAA,CAA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SAAA,CAAA06C,CAAAA,CAAW,QAAAJ,CAAQ,CAAA,GAAM,CAC1B,GAAI,CAACt6C,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,4DAA4D,CAAA,CAE9E,OAAO,CACL,CACE,aAAA,CACA,CACE,GAAI,OAAA,CACJ,cAAA,CAAgB,EAAC,CACjB,sBAAA,CAAwB,CAACA,CAAQ,CAAA,CACjC,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACnB,IAAA,CAAM06C,EACN,MAAA,CAAQ,MAAA,CACR,OAAA,CAAAJ,CACF,CAAC,CACH,CACF,CACF,CACF,CAAA,CACA,MAAA,CACA7yC,CAAAA,CACA,SAAA,CACA,CAAE,aAAA,CAAeI,CAAAA,EAAiB,OAAQ,CAC5C,CACF","file":"index.mjs","sourcesContent":["/**\n * @license bytebuffer.ts (c) 2015 Daniel Wirtz \n * Backing buffer: ArrayBuffer, Accessor: DataView\n * Released under the Apache License, Version 2.0\n * see: https://github.com/dcodeIO/bytebuffer.ts for details\n * modified by @xmcl/bytebuffer\n * And customized for hive-tx\n */\n\nconst EMPTY_BUFFER = new ArrayBuffer(0)\n\n// Lazy-init to avoid crashing on runtimes that lack TextEncoder/TextDecoder\n// (notably React Native with Hermes). Falls back to manual UTF-8 encode/decode.\nlet _encoder: { encode(s: string): Uint8Array } | null = null\nlet _decoder: { decode(b: BufferSource): string } | null = null\n\nfunction getEncoder(): { encode(s: string): Uint8Array } {\n if (!_encoder) {\n if (typeof TextEncoder !== 'undefined') {\n _encoder = new TextEncoder()\n } else {\n _encoder = {\n encode(s: string): Uint8Array {\n // Manual UTF-8 encode fallback\n const utf8: number[] = []\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i)\n if (c < 0x80) {\n utf8.push(c)\n } else if (c < 0x800) {\n utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n const next = s.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n return new Uint8Array(utf8)\n },\n }\n }\n }\n return _encoder\n}\n\nfunction getDecoder(): { decode(b: BufferSource): string } {\n if (!_decoder) {\n if (typeof TextDecoder !== 'undefined') {\n _decoder = new TextDecoder()\n } else {\n _decoder = {\n decode(b: BufferSource): string {\n const bytes = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array((b as ArrayBufferView).buffer, (b as ArrayBufferView).byteOffset, (b as ArrayBufferView).byteLength)\n let result = ''\n for (let i = 0; i < bytes.length; ) {\n const byte = bytes[i]\n let codePoint: number\n if (byte < 0x80) { codePoint = byte; i += 1 }\n else if ((byte & 0xe0) === 0xc0) { codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2 }\n else if ((byte & 0xf0) === 0xe0) { codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3 }\n else { codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); i += 4 }\n if (codePoint <= 0xffff) { result += String.fromCharCode(codePoint) }\n else { codePoint -= 0x10000; result += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) }\n }\n return result\n },\n }\n }\n }\n return _decoder\n}\n\nexport class ByteBuffer {\n static LITTLE_ENDIAN = true\n static BIG_ENDIAN = false\n static DEFAULT_CAPACITY = 16\n static DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN\n\n buffer: ArrayBufferLike\n view: DataView\n offset: number\n markedOffset: number\n limit: number\n littleEndian: boolean\n\n constructor(\n capacity: number = ByteBuffer.DEFAULT_CAPACITY,\n littleEndian: boolean = ByteBuffer.DEFAULT_ENDIAN\n ) {\n this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity)\n this.view = capacity === 0 ? new DataView(EMPTY_BUFFER) : new DataView(this.buffer)\n this.offset = 0\n this.markedOffset = -1\n this.limit = capacity\n this.littleEndian = littleEndian\n }\n\n static allocate(capacity?: number, littleEndian?: boolean): ByteBuffer {\n return new ByteBuffer(capacity, littleEndian)\n }\n\n static concat(\n buffers: Array,\n littleEndian?: boolean\n ): ByteBuffer {\n let capacity = 0\n for (let i = 0; i < buffers.length; ++i) {\n const buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n capacity += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n capacity += buf.length\n } else if (buf instanceof ArrayBuffer) {\n capacity += buf.byteLength\n } else if (Array.isArray(buf)) {\n capacity += buf.length\n } else {\n throw TypeError('Illegal buffer')\n }\n }\n\n if (capacity === 0) {\n return new ByteBuffer(0, littleEndian)\n }\n\n const bb = new ByteBuffer(capacity, littleEndian)\n const view = new Uint8Array(bb.buffer)\n let offset = 0\n\n for (let i = 0; i < buffers.length; ++i) {\n let buf = buffers[i]\n if (buf instanceof ByteBuffer) {\n view.set(new Uint8Array(buf.buffer, buf.offset, buf.limit - buf.offset), offset)\n offset += buf.limit - buf.offset\n } else if (buf instanceof Uint8Array) {\n view.set(buf, offset)\n offset += buf.length\n } else if (buf instanceof ArrayBuffer) {\n view.set(new Uint8Array(buf), offset)\n offset += buf.byteLength\n } else {\n // Array\n view.set(buf as number[], offset)\n offset += (buf as number[]).length\n }\n }\n\n bb.limit = bb.offset = offset\n bb.offset = 0\n return bb\n }\n\n static wrap(\n buffer: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n littleEndian?: boolean\n ): ByteBuffer {\n if (buffer instanceof ByteBuffer) {\n const bb = buffer.clone()\n bb.markedOffset = -1\n return bb\n }\n\n let bb: ByteBuffer\n if (buffer instanceof Uint8Array) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.length > 0) {\n bb.buffer = buffer.buffer\n bb.offset = buffer.byteOffset\n bb.limit = buffer.byteOffset + buffer.byteLength\n bb.view = new DataView(buffer.buffer)\n }\n } else if (buffer instanceof ArrayBuffer) {\n bb = new ByteBuffer(0, littleEndian)\n if (buffer.byteLength > 0) {\n bb.buffer = buffer\n bb.offset = 0\n bb.limit = buffer.byteLength\n bb.view = buffer.byteLength > 0 ? new DataView(buffer) : new DataView(EMPTY_BUFFER)\n }\n } else if (Array.isArray(buffer)) {\n bb = new ByteBuffer(buffer.length, littleEndian)\n bb.limit = buffer.length\n new Uint8Array(bb.buffer).set(buffer)\n } else {\n throw TypeError('Illegal buffer')\n }\n\n return bb\n }\n\n writeBytes(\n source: ByteBuffer | ArrayBuffer | Uint8Array | number[],\n offset?: number\n ): ByteBuffer {\n return this.append(source, offset)\n }\n\n writeInt8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setInt8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeByte(value: number, offset?: number): ByteBuffer {\n return this.writeInt8(value, offset)\n }\n\n writeUint8(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 1 > this.buffer.byteLength) {\n this.resize(offset + 1)\n }\n\n this.view.setUint8(offset, value)\n\n if (relative) this.offset += 1\n return this\n }\n\n writeUInt8(value: number, offset?: number): ByteBuffer {\n return this.writeUint8(value, offset)\n }\n\n readUint8(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint8(offset)\n if (relative) this.offset += 1\n return value\n }\n\n readUInt8(offset?: number): number {\n return this.readUint8(offset)\n }\n\n writeInt16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setInt16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeShort(value: number, offset?: number): ByteBuffer {\n return this.writeInt16(value, offset)\n }\n\n writeUint16(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 2 > this.buffer.byteLength) {\n this.resize(offset + 2)\n }\n\n this.view.setUint16(offset, value, this.littleEndian)\n\n if (relative) this.offset += 2\n return this\n }\n\n writeUInt16(value: number, offset?: number): ByteBuffer {\n return this.writeUint16(value, offset)\n }\n\n writeInt32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setInt32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeInt(value: number, offset?: number): ByteBuffer {\n return this.writeInt32(value, offset)\n }\n\n writeUint32(value: number, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (offset + 4 > this.buffer.byteLength) {\n this.resize(offset + 4)\n }\n\n this.view.setUint32(offset, value, this.littleEndian)\n\n if (relative) this.offset += 4\n return this\n }\n\n writeUInt32(value: number, offset?: number): ByteBuffer {\n return this.writeUint32(value, offset)\n }\n\n readUint32(offset?: number): number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getUint32(offset, this.littleEndian)\n if (relative) {\n this.offset += 4\n }\n return value\n }\n\n readUInt32 = this.readUint32\n\n append(source: ByteBuffer | ArrayBuffer | Uint8Array | number[], offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n let src: Uint8Array\n if (source instanceof ByteBuffer) {\n src = new Uint8Array(source.buffer, source.offset, source.limit - source.offset)\n source.offset += src.length\n } else if (source instanceof Uint8Array) {\n src = source\n } else if (source instanceof ArrayBuffer) {\n src = new Uint8Array(source)\n } else {\n src = new Uint8Array(source)\n }\n\n if (src.length <= 0) return this\n\n if (offset + src.length > this.buffer.byteLength) {\n this.resize(offset + src.length)\n }\n\n new Uint8Array(this.buffer).set(src, offset)\n\n if (relative) this.offset += src.length\n return this\n }\n\n clone(copy?: boolean): ByteBuffer {\n const bb = new ByteBuffer(0, this.littleEndian)\n if (copy) {\n bb.buffer = new ArrayBuffer(this.buffer.byteLength)\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer))\n bb.view = new DataView(bb.buffer)\n } else {\n bb.buffer = this.buffer\n bb.view = this.view\n }\n bb.offset = this.offset\n bb.markedOffset = this.markedOffset\n bb.limit = this.limit\n return bb\n }\n\n copy(begin?: number, end?: number): ByteBuffer {\n if (begin === undefined) begin = this.offset\n if (end === undefined) end = this.limit\n\n if (begin === end) {\n return new ByteBuffer(0, this.littleEndian)\n }\n\n const capacity = end - begin\n const bb = new ByteBuffer(capacity, this.littleEndian)\n bb.offset = 0\n bb.limit = capacity\n\n new Uint8Array(bb.buffer).set(new Uint8Array(this.buffer).subarray(begin, end), 0)\n return bb\n }\n\n copyTo(\n target: ByteBuffer,\n targetOffset?: number,\n sourceOffset?: number,\n sourceLimit?: number\n ): ByteBuffer {\n const targetRelative = typeof targetOffset === 'undefined'\n const relative = typeof sourceOffset === 'undefined'\n targetOffset = targetRelative ? target.offset : targetOffset!\n sourceOffset = relative ? this.offset : sourceOffset!\n sourceLimit = sourceLimit === undefined ? this.limit : sourceLimit\n\n const len = sourceLimit - sourceOffset\n if (len === 0) return target\n\n target.ensureCapacity(targetOffset + len)\n new Uint8Array(target.buffer).set(\n new Uint8Array(this.buffer).subarray(sourceOffset, sourceLimit),\n targetOffset\n )\n\n if (relative) this.offset += len\n if (targetRelative) target.offset += len\n return this\n }\n\n ensureCapacity(capacity: number): ByteBuffer {\n let current = this.buffer.byteLength\n if (current < capacity) {\n return this.resize((current *= 2) > capacity ? current : capacity)\n }\n return this\n }\n\n flip(): ByteBuffer {\n this.limit = this.offset\n this.offset = 0\n return this\n }\n\n resize(capacity: number): ByteBuffer {\n if (this.buffer.byteLength < capacity) {\n const buffer = new ArrayBuffer(capacity)\n new Uint8Array(buffer).set(new Uint8Array(this.buffer))\n this.buffer = buffer\n this.view = new DataView(buffer)\n }\n return this\n }\n\n skip(length: number): ByteBuffer {\n this.offset += length\n return this\n }\n\n writeInt64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigInt64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeLong(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeInt64(value, offset)\n }\n\n readInt64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigInt64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readLong(offset?: number): bigint {\n return this.readInt64(offset)\n }\n\n writeUint64(value: number | bigint, offset?: number): ByteBuffer {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n if (typeof value === 'number') value = BigInt(value)\n\n if (offset + 8 > this.buffer.byteLength) {\n this.resize(offset + 8)\n }\n\n this.view.setBigUint64(offset, value, this.littleEndian)\n\n if (relative) this.offset += 8\n return this\n }\n\n writeUInt64(value: number | bigint, offset?: number): ByteBuffer {\n return this.writeUint64(value, offset)\n }\n\n readUint64(offset?: number): bigint {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const value = this.view.getBigUint64(offset, this.littleEndian)\n if (relative) this.offset += 8\n return value\n }\n\n readUInt64(offset?: number): bigint {\n return this.readUint64(offset)\n }\n\n toBuffer(forceCopy?: boolean): ArrayBufferLike {\n const offset = this.offset\n const limit = this.limit\n if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) {\n return this.buffer\n }\n if (offset === limit) return EMPTY_BUFFER\n return this.buffer.slice(offset, limit)\n }\n\n toArrayBuffer(forceCopy?: boolean): ArrayBufferLike {\n return this.toBuffer(forceCopy)\n }\n\n writeVarint32(value: number, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const size = this.calculateVarint32(value)\n if (offset + size > this.buffer.byteLength) {\n this.resize(offset + size)\n }\n\n value >>>= 0\n while (value >= 0x80) {\n this.view.setUint8(offset++, (value & 0x7f) | 0x80)\n value >>>= 7\n }\n this.view.setUint8(offset++, value)\n\n if (relative) {\n this.offset = offset\n return this\n }\n return size\n }\n\n readVarint32(offset?: number): number | { value: number; length: number } {\n const relative = typeof offset === 'undefined'\n if (typeof offset === 'undefined') {\n offset = this.offset\n }\n let c = 0\n let value = 0 >>> 0\n let b: number\n do {\n b = this.view.getUint8(offset++)\n if (c < 5) {\n value |= (b & 0x7f) << (7 * c)\n }\n ++c\n } while ((b & 0x80) !== 0)\n value |= 0\n\n if (relative) {\n this.offset = offset\n return value\n }\n return { value, length: c }\n }\n\n calculateVarint32(value: number): number {\n value = value >>> 0\n if (value < 1 << 7) return 1\n else if (value < 1 << 14) return 2\n else if (value < 1 << 21) return 3\n else if (value < 1 << 28) return 4\n else return 5\n }\n\n writeVString(str: string, offset?: number): ByteBuffer | number {\n const relative = typeof offset === 'undefined'\n let currentOffset = relative ? this.offset : offset!\n\n const encoded = getEncoder().encode(str)\n const len = encoded.length\n const lenVarintSize = this.calculateVarint32(len)\n\n if (currentOffset + lenVarintSize + len > this.buffer.byteLength) {\n this.resize(currentOffset + lenVarintSize + len)\n }\n\n this.writeVarint32(len, currentOffset)\n currentOffset += lenVarintSize\n\n new Uint8Array(this.buffer).set(encoded, currentOffset)\n currentOffset += len\n\n if (relative) {\n this.offset = currentOffset\n return this\n }\n return currentOffset - (offset || 0)\n }\n\n readVString(offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n const start = offset\n const lenResult = this.readVarint32(offset) as { value: number; length: number }\n const lenValue = lenResult.value\n const lenLength = lenResult.length\n\n offset += lenLength\n\n // TextDecoder can take Uint8Array view directly\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, lenValue))\n offset += lenValue\n\n if (relative) {\n this.offset = offset\n return str\n } else {\n return {\n string: str,\n length: offset - start\n }\n }\n }\n\n readUTF8String(length: number, offset?: number): string | { string: string; length: number } {\n const relative = typeof offset === 'undefined'\n if (relative) offset = this.offset\n else offset = offset!\n\n // const strBuffer = this.buffer.slice(offset, end)\n // Faster to view if Shared? No, Decoder takes buffer or view.\n // Making a view is cheap.\n // But DataView vs Uint8Array. TextDecoder takes BufferSource (ArrayBuffer or ArrayBufferView).\n const str = getDecoder().decode(new Uint8Array(this.buffer as ArrayBuffer, offset, length))\n\n if (relative) {\n this.offset += length\n return str\n } else {\n return {\n string: str,\n length\n }\n }\n }\n}\n","import type { APIMethods } from './api-types'\n\n/**\n * Unified configuration for Hive blockchain connectivity.\n * This is the single source of truth for node endpoints, timeouts, and chain settings.\n * Mutate this object directly or use ConfigManager.setHiveNodes() for validated updates.\n */\nexport const config = {\n /**\n * Array of Hive API node endpoints for load balancing and failover.\n */\n /*\n * techcoderx.com is deliberately absent: its condenser_api.get_accounts serves\n * account rows with posting_json_metadata stripped to \"\" while balances and\n * reputation are correct. That is a well-formed result, so it passes shape\n * validation and the health tracker keeps it ranked by latency alone.\n *\n * Wallet token visibility is read entirely from profile.tokens[].meta.show in\n * that metadata, so a stripped row reads as \"this user enabled nothing\" and the\n * wallet silently falls back to HIVE/HP/HBD/Points. getAccountFullQueryOptions\n * cross-checks against the hivemind profile and re-reads, but that guard only\n * fires when hivemind reports profile *values* — an account whose metadata is\n * just `tokens` (no name/about/image) has none, so it would slip through.\n * Keeping the node out of the pool removes the dependency on that guard.\n *\n * Note this is RPC-only: the same host serves full metadata over its REST\n * (hafbe) endpoint, so it remains valid in `restNodes`.\n */\n nodes: [\n 'https://api.hive.blog',\n 'https://api.deathwing.me',\n 'https://api.openhive.network',\n 'https://api.syncad.com',\n 'https://rpc.mahdiyari.info',\n ],\n\n /**\n * Array of Hive API node endpoints that support REST APIs.\n * Note: Without the trailing /\n */\n restNodes: [\n 'https://api.hive.blog',\n 'https://rpc.mahdiyari.info',\n 'https://api.syncad.com',\n 'https://hiveapi.actifit.io',\n 'https://api.c0ff33a.uk'\n ],\n\n /**\n * Per-API REST node override. Some APIs are served by only a subset of\n * nodes; list just those capable hosts here so callREST never burns its\n * (small) retry budget on nodes that 404/503 the API, and a cold start\n * hits a capable node immediately. Any API not listed falls back to\n * `restNodes`. The health tracker still orders *within* this list.\n *\n * hivesense: empirically only ~2 public nodes serve /hivesense-api (the\n * other configured nodes 404/503 it; Ecency's own was decommissioned), so\n * pin them — otherwise the health tracker keeps rediscovering incapable\n * nodes each cooldown and cold starts waste attempts.\n */\n restNodesByApi: {\n hivesense: ['https://api.hive.blog', 'https://api.syncad.com']\n } as Partial>,\n\n /**\n * User-Agent sent on server-side (Node) HTTP requests to Hive nodes.\n *\n * Node's built-in fetch (undici) sends a bare `User-Agent: node` when none is\n * set, which is indistinguishable from any random Node script in node/CDN\n * analytics. A descriptive value lets operators tell their own SSR/server\n * traffic apart from anonymous scrapers. Only applied in Node — browsers\n * forbid overriding User-Agent (it is silently dropped) and React Native sets\n * its own native UA, so client and mobile traffic are untouched. Override via\n * `ConfigManager.setUserAgent()` (or `setUserAgent()` from `@ecency/sdk/hive`).\n */\n userAgent: 'ecency-sdk',\n\n /**\n * The Hive blockchain chain ID for transaction signing and verification.\n */\n chain_id: 'beeab0de00000000000000000000000000000000000000000000000000000000',\n\n /**\n * Address prefix used for public key formatting (STM for mainnet).\n */\n address_prefix: 'STM',\n\n /**\n * Timeout in milliseconds for read API calls (get_content, get_accounts, etc.).\n * Kept short so the health tracker can fail over to another node quickly.\n */\n timeout: 5_000,\n\n /**\n * Timeout in milliseconds for broadcast API calls.\n * Longer than read timeout because broadcast_transaction_synchronous waits\n * for block inclusion, which depends on the 3-second block interval and\n * network conditions.\n */\n broadcastTimeout: 15_000,\n\n /**\n * Number of retry attempts for failed API calls before throwing an error.\n * Total attempts = retry + 1. With ~7 nodes in the list, a budget of 5\n * means callRPC iterates through 6 distinct nodes before giving up, so a\n * single sick node (or two) can't surface as an unhandled error to the\n * caller while the rest of the list is healthy.\n */\n retry: 5,\n\n /**\n * Tail-latency resilience for READ calls. Motivation: on a shared public-node\n * pool a node can slow down or throttle *mid-request*; a fixed `timeout` means\n * the caller only notices after the full window, and under SSR concurrency\n * those stalled renders pile up. Two mechanisms, both scoped to reads only\n * (broadcasts never hedge and keep their fixed `broadcastTimeout`):\n *\n * - Adaptive per-attempt timeout (`adaptiveTimeout`, default ON): when a\n * node has a usable latency profile (EWMA), the per-attempt timeout becomes\n * `min(callerTimeout, max(floorMs, factor × EWMA))` — a node running far\n * above its own baseline is abandoned early and failover starts sooner.\n * Never *raises* the caller's timeout; unprofiled nodes keep it unchanged.\n *\n * - Hedged requests (`hedge`, default OFF — opt in via `setResilience`): if\n * the primary attempt is still pending after `max(hedgeDelayFloorMs,\n * hedgeDelayFactor × EWMA)`, a duplicate request is fired at the next\n * healthy untried node and the first success wins (the loser is aborted).\n * A token bucket (`hedgeBucketCapacity` burst, refilled by\n * `hedgeRefillPerSuccess` per un-hedged success) caps hedges to roughly\n * `hedgeRefillPerSuccess` of traffic, so only the slow tail hedges — and\n * under pool-wide slowness the bucket drains and hedging auto-disables\n * instead of amplifying load into public-node rate limits.\n */\n resilience: {\n adaptiveTimeout: true,\n adaptiveTimeoutFloorMs: 2_000,\n adaptiveTimeoutFactor: 4,\n hedge: false,\n hedgeDelayFloorMs: 750,\n hedgeDelayFactor: 2,\n hedgeBucketCapacity: 10,\n hedgeRefillPerSuccess: 0.1,\n /**\n * Wall-clock budget for one read call across ALL failover attempts, as a\n * multiple of the per-attempt timeout: no NEW attempt starts past\n * `totalBudgetFactor × timeout` (an in-flight attempt still finishes its\n * own window). Bounds the pathological pool-wide-slowness walk — without\n * it a read could hold its caller for (retry+1) × timeout ≈ 30s, which\n * under SSR concurrency is a memory pile-up, the exact incident this\n * feature exists for. Applies to reads only (callRPC / callREST);\n * broadcasts keep their try-each-node-once semantics.\n */\n totalBudgetFactor: 2\n }\n}\n\n/** Shape of the `config.resilience` bag (see its doc comment). */\nexport type ResilienceOptions = typeof config.resilience\n\n/**\n * Validated setter for the Hive RPC node list — replaces `config.nodes`.\n * Trims, drops non-http(s) entries, and de-dupes (order-preserving). A no-op\n * if nothing valid remains, so a bad input can't empty the list.\n *\n * Lives here, in the React-free `hive-tx` core, on purpose: it must be\n * reachable from BOTH the full `@ecency/sdk` entry (via\n * `ConfigManager.setHiveNodes`, which delegates here) and the lean\n * `@ecency/sdk/hive` server/CLI entry — without dragging react-query or the\n * DMCA/ReDoS surface of `ConfigManager` into the lean entry. Within a single\n * bundle this mutates the one `config` instance `callRPC` reads; the\n * cross-bundle single-instance guarantee is a separate (build-level) concern.\n */\n/**\n * Trim, drop non-string / non-http(s), and de-dupe (order-preserving) a node\n * list. Shared by `setNodes` and the REST-node setters below so all three\n * normalize identically.\n */\nconst sanitizeNodeList = (nodes: unknown): string[] =>\n Array.isArray(nodes)\n ? [\n ...new Set(\n nodes\n .filter((n): n is string => typeof n === 'string')\n // Trim, then strip trailing slashes so REST paths concatenate cleanly:\n // `callREST` builds `node + '/status-api'`, and a `https://host/` node would\n // otherwise yield `https://host//status-api`, which several HAF nodes 404.\n // De-dupe AFTER normalizing so `host` and `host/` collapse to one entry.\n .map((n) => n.trim().replace(/\\/+$/, ''))\n .filter((n) => n.length > 0 && /^https?:\\/\\/.+/.test(n))\n )\n ]\n : []\n\nexport const setNodes = (nodes: string[]): void => {\n const validNodes = sanitizeNodeList(nodes)\n if (!validNodes.length) return\n config.nodes = validNodes\n}\n\n/**\n * Validated setter for the REST-API node list — replaces `config.restNodes`.\n * Same shape/guarantees as `setNodes` (trim, drop non-http(s), de-dupe, no-op on\n * empty). Exists because `restNodes` is otherwise baked into the SDK: an app that\n * wants to add/remove a REST host (e.g. drop an own node it is decommissioning, or\n * widen the public pool) previously had to fork + republish the SDK. With this, the\n * REST pool is app-configurable at runtime exactly like the read pool. Lives in the\n * React-free `hive-tx` core so both the full `@ecency/sdk` entry and the lean\n * `@ecency/sdk/hive` entry can reach it.\n */\nexport const setRestNodes = (nodes: string[]): void => {\n const valid = sanitizeNodeList(nodes)\n if (!valid.length) return\n config.restNodes = valid\n}\n\n/**\n * Merge validated per-API REST node overrides into `config.restNodesByApi`.\n * For each entry: a non-empty, valid list pins that API to those hosts; an empty or\n * all-invalid list REMOVES the pin so the API falls back to `restNodes`. Other APIs'\n * existing pins (e.g. the built-in `hivesense`) are preserved. Lets an app pin the\n * APIs it actually uses to known-capable hosts (so `callREST` never burns its small\n * retry budget on a node that 404/503s the API) without an SDK republish.\n */\nexport const setRestNodesByApi = (\n map: Partial>\n): void => {\n if (!map || typeof map !== 'object') return\n const next: Partial> = { ...config.restNodesByApi }\n for (const [api, list] of Object.entries(map)) {\n const valid = sanitizeNodeList(list)\n if (valid.length) {\n next[api as APIMethods] = valid\n } else {\n delete next[api as APIMethods]\n }\n }\n config.restNodesByApi = next\n}\n\n/**\n * Validated setter for the User-Agent sent on server-side (Node) requests.\n * Trims the input and ignores an empty value so a bad input can't blank out the\n * header. Like `setNodes`, it lives in the React-free `hive-tx` core so it is\n * reachable from both the full `@ecency/sdk` entry (via\n * `ConfigManager.setUserAgent`) and the lean `@ecency/sdk/hive` server/CLI entry.\n */\nexport const setUserAgent = (ua: string): void => {\n // Defensive against plain-JS / React Native callers that may pass a non-string\n // despite the `string` type (avoids throwing on `.trim()`).\n if (typeof ua !== 'string') return\n const value = ua.trim()\n // Ignore blank values, and reject control characters (CR, LF, and other\n // C0/DEL controls). An invalid header value would otherwise be stored and make\n // every subsequent fetch throw, and rejecting CR/LF closes a header-injection\n // vector for any caller that builds the UA from untrusted input.\n if (!value || /[\\u0000-\\u001f\\u007f]/.test(value)) return\n config.userAgent = value\n}\n\n/**\n * Validated partial setter for `config.resilience` (adaptive read timeouts +\n * hedged requests — see the field's doc comment). Booleans must be booleans;\n * numeric fields must be finite and positive, with the refill rate additionally\n * capped at 1 so a typo can't turn the tail-hedge into a traffic doubler\n * (refill ≤ 1 ⇒ hedges can never exceed un-hedged successes). Invalid values\n * are ignored field-by-field, so one bad entry can't block the rest. Lives in\n * the React-free `hive-tx` core (like the other setters) so both `@ecency/sdk`\n * (via `ConfigManager.setResilience`) and the lean `@ecency/sdk/hive` entry\n * can reach it.\n */\nexport const setResilience = (opts: Partial): void => {\n if (!opts || typeof opts !== 'object') return\n const r = config.resilience\n const bool = (v: unknown): v is boolean => typeof v === 'boolean'\n const pos = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0\n if (bool(opts.adaptiveTimeout)) r.adaptiveTimeout = opts.adaptiveTimeout\n // Floor must stay ≥ the tracker's slow-failure recording floor (2s): the\n // safety argument for adaptive timeouts is that an abort at the window IS\n // recorded as a slow sample, growing the EWMA so the window self-corrects\n // upward. A floor below 2s would abort without recording — the window could\n // never converge and a too-tight profile would starve that call forever.\n if (pos(opts.adaptiveTimeoutFloorMs)) {\n r.adaptiveTimeoutFloorMs = Math.max(opts.adaptiveTimeoutFloorMs, 2_000)\n }\n if (pos(opts.adaptiveTimeoutFactor)) r.adaptiveTimeoutFactor = opts.adaptiveTimeoutFactor\n if (bool(opts.hedge)) r.hedge = opts.hedge\n if (pos(opts.hedgeDelayFloorMs)) r.hedgeDelayFloorMs = opts.hedgeDelayFloorMs\n if (pos(opts.hedgeDelayFactor)) r.hedgeDelayFactor = opts.hedgeDelayFactor\n if (pos(opts.hedgeBucketCapacity)) r.hedgeBucketCapacity = opts.hedgeBucketCapacity\n // Refill must stay ≤ 1: at 1 token per success the hedge rate could reach\n // 100% of traffic, defeating the \"tail only\" contract. Cap rather than reject\n // so a caller asking for \"more hedging\" gets the safe maximum.\n if (pos(opts.hedgeRefillPerSuccess)) {\n r.hedgeRefillPerSuccess = Math.min(opts.hedgeRefillPerSuccess, 1)\n }\n // Below 1 the budget could not even cover the configured per-attempt window.\n if (pos(opts.totalBudgetFactor)) {\n r.totalBudgetFactor = Math.max(opts.totalBudgetFactor, 1)\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport class Signature {\n data: Uint8Array\n recovery: number\n private compressed: boolean\n\n /**\n * Creates a new Signature instance.\n * @param data Raw signature data (64 bytes)\n * @param recovery Recovery byte (0-3)\n * @param compressed Whether signature is compressed (default: true)\n */\n constructor(data: Uint8Array, recovery: number, compressed?: boolean) {\n this.data = data\n this.recovery = recovery\n this.compressed = compressed ?? true\n }\n\n /**\n * Creates a Signature from a hex string.\n * @param string 130-character hex string containing signature and recovery data\n * @returns New Signature instance\n * @throws Error if input is not a string\n */\n static from(string: string) {\n if (typeof string === 'string') {\n const temp = hexToBytes(string)\n let recovery = parseInt(bytesToHex(temp.subarray(0, 1)), 16) - 31\n let compressed = true\n // non-compressed signatures have -4\n // https://github.com/bitcoin/bitcoin/blob/95ea54ba089610019a74c1176a2c7c0dba144b1c/src/key.cpp#L257\n if (recovery < 0) {\n compressed = false\n recovery = recovery + 4\n }\n const data = temp.subarray(1)\n return new Signature(data, recovery, compressed)\n } else {\n throw new Error('Expected string for data')\n }\n }\n\n /**\n * Converts signature to 65-byte buffer format.\n * @returns 65-byte buffer containing recovery byte + signature data\n */\n toBuffer() {\n const buffer = new Uint8Array(65).fill(0)\n if (this.compressed) {\n buffer[0] = (this.recovery + 31) & 0xff\n } else {\n buffer[0] = (this.recovery + 27) & 0xff\n }\n buffer.set(this.data, 1)\n return buffer\n }\n\n /**\n * Returns signature as 130-character hex string.\n * @returns Hex string representation of signature\n */\n customToString() {\n return bytesToHex(this.toBuffer())\n }\n\n /**\n * Returns signature as 130-character hex string.\n * Overrides Object.prototype.toString() so that String(sig) and\n * template literals produce the hex representation instead of \"[object Object]\".\n * @returns Hex string representation of signature\n */\n toString() {\n return this.customToString()\n }\n\n /**\n * Recovers the public key from this signature and message.\n * @param message 32-byte message hash (Uint8Array) or 64-character hex string\n * @returns PublicKey that created this signature\n * @throws Error if message is not a valid 32-byte SHA256 hash\n */\n getPublicKey(message: Uint8Array | string): PublicKey {\n if (\n (message instanceof Uint8Array && message.length !== 32) ||\n (typeof message === 'string' && message.length !== 64)\n ) {\n throw new Error('Expected a valid sha256 hash as message')\n }\n if (typeof message === 'string') {\n message = hexToBytes(message)\n }\n const sig = secp256k1.Signature.fromBytes(this.data, 'compact')\n const temp = new secp256k1.Signature(sig.r, sig.s, this.recovery)\n return new PublicKey(temp.recoverPublicKey(message).toBytes())\n }\n}\n","import { ripemd160 } from '@noble/hashes/legacy.js'\nimport bs58 from 'bs58'\nimport { config } from '../config'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { Signature } from './Signature'\n\nexport class PublicKey {\n key: Uint8Array\n prefix: string\n\n /**\n * Creates a new PublicKey instance from raw bytes.\n * @param key Raw public key bytes (33 bytes, compressed format)\n * @param prefix Optional address prefix (defaults to the current config.address_prefix)\n */\n constructor(key: Uint8Array, prefix?: string) {\n this.key = key\n // Read config at call time so runtime mutations to config.address_prefix\n // (e.g. switching to a non-mainnet network) take effect for new instances.\n this.prefix = prefix ?? config.address_prefix\n }\n\n /**\n * Creates a PublicKey from a string representation.\n * The expected prefix is read from config.address_prefix at call time, so\n * consumers can switch networks at runtime.\n * @param wif Public key string (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n * @returns New PublicKey instance\n * @throws Error if the prefix, length, checksum, or curve point is invalid\n */\n static fromString(wif: string): PublicKey {\n const expectedPrefix = config.address_prefix\n if (typeof wif !== 'string' || wif.length <= expectedPrefix.length) {\n throw new Error('Invalid public key')\n }\n const prefix = wif.slice(0, expectedPrefix.length)\n if (prefix !== expectedPrefix) {\n throw new Error(`Public key must start with ${expectedPrefix}`)\n }\n let buffer: Uint8Array\n try {\n buffer = bs58.decode(wif.slice(expectedPrefix.length))\n } catch {\n throw new Error('Invalid public key encoding')\n }\n // 33-byte compressed secp256k1 point + 4-byte RIPEMD160 checksum\n if (buffer.length !== 37) {\n throw new Error('Invalid public key length')\n }\n const key = buffer.subarray(0, 33)\n const checksum = buffer.subarray(33, 37)\n const expectedChecksum = ripemd160(key).subarray(0, 4)\n if (!isUint8ArrayEqual(checksum, expectedChecksum)) {\n throw new Error('Public key checksum mismatch')\n }\n try {\n secp256k1.Point.fromBytes(key)\n } catch {\n throw new Error('Invalid public key')\n }\n return new PublicKey(key, prefix)\n }\n\n /**\n * Creates a PublicKey from a string or returns the instance if already a PublicKey.\n * @param value Public key string or PublicKey instance\n * @returns New or existing PublicKey instance\n */\n static from(value: string | PublicKey): PublicKey {\n if (value instanceof PublicKey) {\n return value\n } else {\n return PublicKey.fromString(value as string)\n }\n }\n\n /**\n * Verifies a signature against a message hash.\n * @param message 32-byte message hash to verify\n * @param signature Signature to verify\n * @returns True if signature is valid, false otherwise\n */\n verify(message: Uint8Array, signature: Signature | string): boolean {\n if (typeof signature === 'string') {\n signature = Signature.from(signature)\n }\n return secp256k1.verify(signature.data, message, this.key, {\n prehash: false,\n format: 'compact'\n })\n }\n\n /**\n * Returns the public key as a string for storage or transmission.\n * @returns Public key string with prefix (e.g., \"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA\")\n */\n toString(): string {\n return encodePublic(this.key, this.prefix)\n }\n\n /**\n * Returns JSON representation (same as toString()).\n * @returns Public key string\n */\n toJSON(): string {\n return this.toString()\n }\n\n /**\n * Returns a string representation for debugging.\n * @returns Formatted public key string\n */\n inspect(): string {\n return `PublicKey: ${this.toString()}`\n }\n}\n\nconst encodePublic = (key: Uint8Array, prefix: string): string => {\n const checksum = ripemd160(key)\n return prefix + bs58.encode(new Uint8Array([...key, ...checksum.subarray(0, 4)]))\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.byteLength !== b.byteLength) return false\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false\n }\n return true\n}\n","/** Class representing a hive asset,\n * e.g. `1.000 HIVE` or `12.112233 VESTS`. */\nexport class Asset {\n amount: number\n symbol: string\n\n constructor(amount: number, symbol: string) {\n this.amount = amount\n this.symbol = symbol === 'HIVE' ? 'STEEM' : symbol === 'HBD' ? 'SBD' : symbol\n }\n\n /** Create a new Asset instance from a string, e.g. `42.000 HIVE`. */\n static fromString(string: string, expectedSymbol: string | null = null): Asset {\n const [amountString, symbol] = string.split(' ')\n if (['STEEM', 'VESTS', 'SBD', 'TESTS', 'TBD', 'HIVE', 'HBD'].indexOf(symbol) === -1) {\n throw new Error(`Invalid asset symbol: ${symbol}`)\n }\n if (expectedSymbol && symbol !== expectedSymbol) {\n throw new Error(`Invalid asset, expected symbol: ${expectedSymbol} got: ${symbol}`)\n }\n const amount = Number.parseFloat(amountString)\n if (!Number.isFinite(amount)) {\n throw new Error(`Invalid asset amount: ${amountString}`)\n }\n return new Asset(amount, symbol)\n }\n\n /**\n * Convenience to create new Asset.\n * @param symbol Symbol to use when created from number. Will also be used to validate\n * the asset, throws if the passed value has a different symbol than this.\n */\n static from(value: number | string | Asset, symbol?: string | null): Asset {\n if (value instanceof Asset) {\n if (symbol && value.symbol !== symbol) {\n throw new Error(`Invalid asset, expected symbol: ${symbol} got: ${value.symbol}`)\n }\n return value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n return new Asset(value, symbol || 'STEEM')\n } else if (typeof value === 'string') {\n return Asset.fromString(value, symbol)\n } else {\n throw new Error(`Invalid asset '${String(value)}'`)\n }\n }\n\n // We convert HIVE & HBD strings to STEEM & SBD because the serialization should be based on STEEM & SBD\n\n /** Return asset precision. */\n getPrecision() {\n switch (this.symbol) {\n case 'TESTS':\n case 'TBD':\n case 'STEEM':\n case 'SBD':\n case 'HBD':\n case 'HIVE':\n return 3\n case 'VESTS':\n return 6\n default:\n return 3\n }\n }\n\n /** Return a string representation of this asset, e.g. `42.000 HIVE`. */\n toString() {\n return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\n/** Buffer wrapper that serializes to a hex-encoded string. */\nexport class HexBuffer {\n buffer: Uint8Array\n /** Convenience to create a new HexBuffer, does not copy data if value passed is already a buffer. */\n static from(value: string | Uint8Array | HexBuffer) {\n if (value instanceof HexBuffer) {\n return value\n } else if (value instanceof Uint8Array) {\n return new HexBuffer(value)\n } else if (typeof value === 'string') {\n return new HexBuffer(hexToBytes(value))\n } else {\n return new HexBuffer(new Uint8Array(value))\n }\n }\n\n constructor(buffer: Uint8Array) {\n this.buffer = buffer\n }\n\n toString() {\n return bytesToHex(this.buffer)\n }\n\n toJSON() {\n return this.toString()\n }\n}\n","import { PublicKey } from './PublicKey'\nimport { Asset } from './Asset'\nimport { HexBuffer } from './HexBuffer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Operation } from '../types'\n\n// Operation ID constants for better maintainability\nconst OPERATION_IDS = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n // pow: 14,\n custom: 15,\n // report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n // pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n // custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49\n} as const\n\ntype OperationId = (typeof OPERATION_IDS)[keyof typeof OPERATION_IDS]\n\nconst VoidSerializer = () => {\n throw new Error('Void can not be serialized')\n}\nconst StringSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeVString(data)\n}\n\nconst Int16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeInt16(data)\n}\n\nconst Int64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeInt64(data)\n}\n\nconst UInt8Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint8(data)\n}\n\nconst UInt16Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint16(data)\n}\n\nconst UInt32Serializer = (buffer: ByteBuffer, data: number) => {\n buffer.writeUint32(data)\n}\n\nconst UInt64Serializer = (buffer: ByteBuffer, data: number | bigint) => {\n buffer.writeUint64(data)\n}\n\nconst BooleanSerializer = (buffer: ByteBuffer, data: number | boolean) => {\n buffer.writeByte(data ? 1 : 0)\n}\n\nconst StaticVariantSerializer = (itemSerializers: any) => {\n // return (buffer: ByteBuffer, data: any[]) => {\n // let id = data[0]\n // const item = data[1]\n // // id was/is supposed to be 0 or integer here but seems to have been changed in e.g. comment_options\n // // extensions: [\n // // [\n // // \"comment_payout_beneficiaries\",\n // // {\n // // \"beneficiaries\": [\n // // {\n // // \"account\": \"vimm\",\n // // \"weight\": 1000\n // // }\n // // ]\n // // }\n // // ]\n // // ]\n // // Keep it here just in case\n // // https://gitlab.syncad.com/hive/hive/-/issues/722\n // // \"comment_payout_beneficiaries\" was 0 and at some point it got changed\n // // It should still be serialized as a 0 or an integer\n // // Now the question is, always 0? will need an example transaction to prove otherwise\n // if (typeof id === 'string') {\n // if (id === 'update_proposal_end_date') {\n // id = 1\n // } else {\n // id = 0\n // }\n // }\n // buffer.writeVarint32(id)\n // itemSerializers[id](buffer, item)\n return (buffer: ByteBuffer, data: any) => {\n const [id, item] = data\n buffer.writeVarint32(id)\n itemSerializers[id](buffer, item)\n }\n}\n\n/**\n * Serialize asset.\n * @note This looses precision for amounts larger than 2^53-1/10^precision.\n * Should not be a problem in real-word usage.\n */\nconst AssetSerializer = (buffer: ByteBuffer, data: string | Asset) => {\n const asset = Asset.from(data)\n const precision = asset.getPrecision()\n buffer.writeInt64(Math.round(asset.amount * Math.pow(10, precision)))\n buffer.writeUint8(precision)\n for (let i = 0; i < 7; i++) {\n buffer.writeUint8(asset.symbol.charCodeAt(i) || 0)\n }\n}\n\nconst DateSerializer = (buffer: ByteBuffer, data: string) => {\n buffer.writeUint32(Math.floor(new Date(data + 'Z').getTime() / 1000))\n}\n\nconst PublicKeySerializer = (buffer: ByteBuffer, data: string | PublicKey) => {\n if (\n data === null ||\n (typeof data === 'string' && data.slice(-39) === '1111111111111111111111111111111114T1Anm')\n ) {\n buffer.append(new Uint8Array(33).fill(0))\n } else {\n buffer.append(PublicKey.from(data).key)\n }\n}\n\nconst BinarySerializer = (size: null | number = null) => {\n return (buffer: ByteBuffer, data: string | Uint8Array | HexBuffer) => {\n data = HexBuffer.from(data)\n const len = data.buffer.length\n if (size) {\n if (len !== size) {\n throw new Error(`Unable to serialize binary. Expected ${size} bytes, got ${len}`)\n }\n } else {\n buffer.writeVarint32(len)\n }\n buffer.append(data.buffer)\n }\n}\n\nconst VariableBinarySerializer = BinarySerializer()\n\nconst FlatMapSerializer = (keySerializer: any, valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(data.length)\n for (const [key, value] of data) {\n keySerializer(buffer, key)\n valueSerializer(buffer, value)\n }\n }\n}\n\nconst ArraySerializer = (itemSerializer: any) => {\n return (buffer: ByteBuffer, data: any[]) => {\n buffer.writeVarint32(data.length)\n for (const item of data) {\n itemSerializer(buffer, item)\n }\n }\n}\n\nconst ObjectSerializer = (keySerializers: any) => {\n return (buffer: ByteBuffer, data: any) => {\n for (const [key, serializer] of keySerializers) {\n try {\n serializer(buffer, data[key])\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n }\n}\n\nconst OptionalSerializer = (valueSerializer: any) => {\n return (buffer: ByteBuffer, data: any | undefined) => {\n if (data !== undefined) {\n buffer.writeByte(1)\n valueSerializer(buffer, data)\n } else {\n buffer.writeByte(0)\n }\n }\n}\n\nconst AuthoritySerializer = ObjectSerializer([\n ['weight_threshold', UInt32Serializer],\n ['account_auths', FlatMapSerializer(StringSerializer, UInt16Serializer)],\n ['key_auths', FlatMapSerializer(PublicKeySerializer, UInt16Serializer)]\n])\n\nconst BeneficiarySerializer = ObjectSerializer([\n ['account', StringSerializer],\n ['weight', UInt16Serializer]\n])\n\nconst PriceSerializer = ObjectSerializer([\n ['base', AssetSerializer],\n ['quote', AssetSerializer]\n])\n\n// const SignedBlockHeaderSerializer = ObjectSerializer([\n// ['previous', BinarySerializer(20)],\n// ['timestamp', DateSerializer],\n// ['witness', StringSerializer],\n// ['transaction_merkle_root', BinarySerializer(20)],\n// ['extensions', ArraySerializer(VoidSerializer)],\n// ['witness_signature', BinarySerializer(65)]\n// ])\n\nconst ChainPropertiesSerializer = ObjectSerializer([\n ['account_creation_fee', AssetSerializer],\n ['maximum_block_size', UInt32Serializer],\n ['hbd_interest_rate', UInt16Serializer]\n])\n\nconst OperationDataSerializer = (operationId: OperationId, definitions: any) => {\n const objectSerializer = ObjectSerializer(definitions)\n return (buffer: ByteBuffer, data: any) => {\n buffer.writeVarint32(operationId)\n objectSerializer(buffer, data)\n }\n}\n\nconst OperationSerializers: Record> = {}\n\nOperationSerializers.account_create = OperationDataSerializer(OPERATION_IDS.account_create, [\n ['fee', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_create_with_delegation = OperationDataSerializer(\n OPERATION_IDS.account_create_with_delegation,\n [\n ['fee', AssetSerializer],\n ['delegation', AssetSerializer],\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update = OperationDataSerializer(OPERATION_IDS.account_update, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.account_witness_proxy = OperationDataSerializer(\n OPERATION_IDS.account_witness_proxy,\n [\n ['account', StringSerializer],\n ['proxy', StringSerializer]\n ]\n)\n\nOperationSerializers.account_witness_vote = OperationDataSerializer(\n OPERATION_IDS.account_witness_vote,\n [\n ['account', StringSerializer],\n ['witness', StringSerializer],\n ['approve', BooleanSerializer]\n ]\n)\n\nOperationSerializers.cancel_transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.cancel_transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer]\n ]\n)\n\nOperationSerializers.change_recovery_account = OperationDataSerializer(\n OPERATION_IDS.change_recovery_account,\n [\n ['account_to_recover', StringSerializer],\n ['new_recovery_account', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.claim_account = OperationDataSerializer(OPERATION_IDS.claim_account, [\n ['creator', StringSerializer],\n ['fee', AssetSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.claim_reward_balance = OperationDataSerializer(\n OPERATION_IDS.claim_reward_balance,\n [\n ['account', StringSerializer],\n ['reward_hive', AssetSerializer],\n ['reward_hbd', AssetSerializer],\n ['reward_vests', AssetSerializer]\n ]\n)\n\nOperationSerializers.comment = OperationDataSerializer(OPERATION_IDS.comment, [\n ['parent_author', StringSerializer],\n ['parent_permlink', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['title', StringSerializer],\n ['body', StringSerializer],\n ['json_metadata', StringSerializer]\n])\n\nOperationSerializers.comment_options = OperationDataSerializer(OPERATION_IDS.comment_options, [\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['max_accepted_payout', AssetSerializer],\n ['percent_hbd', UInt16Serializer],\n ['allow_votes', BooleanSerializer],\n ['allow_curation_rewards', BooleanSerializer],\n [\n 'extensions',\n ArraySerializer(\n StaticVariantSerializer([\n ObjectSerializer([['beneficiaries', ArraySerializer(BeneficiarySerializer)]])\n ])\n )\n ]\n])\n\nOperationSerializers.convert = OperationDataSerializer(OPERATION_IDS.convert, [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n])\n\nOperationSerializers.create_claimed_account = OperationDataSerializer(\n OPERATION_IDS.create_claimed_account,\n [\n ['creator', StringSerializer],\n ['new_account_name', StringSerializer],\n ['owner', AuthoritySerializer],\n ['active', AuthoritySerializer],\n ['posting', AuthoritySerializer],\n ['memo_key', PublicKeySerializer],\n ['json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.custom = OperationDataSerializer(OPERATION_IDS.custom, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['id', UInt16Serializer],\n ['data', VariableBinarySerializer]\n])\n\n// Not used on chain\n// OperationSerializers.custom_binary = OperationDataSerializer(OPERATION_IDS.custom_binary, [\n// ['required_owner_auths', ArraySerializer(StringSerializer)],\n// ['required_active_auths', ArraySerializer(StringSerializer)],\n// ['required_posting_auths', ArraySerializer(StringSerializer)],\n// ['required_auths', ArraySerializer(AuthoritySerializer)],\n// ['id', StringSerializer],\n// ['data', VariableBinarySerializer]\n// ])\n\nOperationSerializers.custom_json = OperationDataSerializer(OPERATION_IDS.custom_json, [\n ['required_auths', ArraySerializer(StringSerializer)],\n ['required_posting_auths', ArraySerializer(StringSerializer)],\n ['id', StringSerializer],\n ['json', StringSerializer]\n])\n\nOperationSerializers.decline_voting_rights = OperationDataSerializer(\n OPERATION_IDS.decline_voting_rights,\n [\n ['account', StringSerializer],\n ['decline', BooleanSerializer]\n ]\n)\n\nOperationSerializers.delegate_vesting_shares = OperationDataSerializer(\n OPERATION_IDS.delegate_vesting_shares,\n [\n ['delegator', StringSerializer],\n ['delegatee', StringSerializer],\n ['vesting_shares', AssetSerializer]\n ]\n)\n\nOperationSerializers.delete_comment = OperationDataSerializer(OPERATION_IDS.delete_comment, [\n ['author', StringSerializer],\n ['permlink', StringSerializer]\n])\n\nOperationSerializers.escrow_approve = OperationDataSerializer(OPERATION_IDS.escrow_approve, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['approve', BooleanSerializer]\n])\n\nOperationSerializers.escrow_dispute = OperationDataSerializer(OPERATION_IDS.escrow_dispute, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['escrow_id', UInt32Serializer]\n])\n\nOperationSerializers.escrow_release = OperationDataSerializer(OPERATION_IDS.escrow_release, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['agent', StringSerializer],\n ['who', StringSerializer],\n ['receiver', StringSerializer],\n ['escrow_id', UInt32Serializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer]\n])\n\nOperationSerializers.escrow_transfer = OperationDataSerializer(OPERATION_IDS.escrow_transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['hbd_amount', AssetSerializer],\n ['hive_amount', AssetSerializer],\n ['escrow_id', UInt32Serializer],\n ['agent', StringSerializer],\n ['fee', AssetSerializer],\n ['json_meta', StringSerializer],\n ['ratification_deadline', DateSerializer],\n ['escrow_expiration', DateSerializer]\n])\n\nOperationSerializers.feed_publish = OperationDataSerializer(OPERATION_IDS.feed_publish, [\n ['publisher', StringSerializer],\n ['exchange_rate', PriceSerializer]\n])\n\nOperationSerializers.limit_order_cancel = OperationDataSerializer(\n OPERATION_IDS.limit_order_cancel,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer]\n ]\n)\n\nOperationSerializers.limit_order_create = OperationDataSerializer(\n OPERATION_IDS.limit_order_create,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['min_to_receive', AssetSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.limit_order_create2 = OperationDataSerializer(\n OPERATION_IDS.limit_order_create2,\n [\n ['owner', StringSerializer],\n ['orderid', UInt32Serializer],\n ['amount_to_sell', AssetSerializer],\n ['exchange_rate', PriceSerializer],\n ['fill_or_kill', BooleanSerializer],\n ['expiration', DateSerializer]\n ]\n)\n\nOperationSerializers.recover_account = OperationDataSerializer(OPERATION_IDS.recover_account, [\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['recent_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\n// Not used on chain\n// OperationSerializers.report_over_production = OperationDataSerializer(\n// OPERATION_IDS.report_over_production,\n// [\n// ['reporter', StringSerializer],\n// ['first_block', SignedBlockHeaderSerializer],\n// ['second_block', SignedBlockHeaderSerializer]\n// ]\n// )\n\nOperationSerializers.request_account_recovery = OperationDataSerializer(\n OPERATION_IDS.request_account_recovery,\n [\n ['recovery_account', StringSerializer],\n ['account_to_recover', StringSerializer],\n ['new_owner_authority', AuthoritySerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.reset_account = OperationDataSerializer(OPERATION_IDS.reset_account, [\n ['reset_account', StringSerializer],\n ['account_to_reset', StringSerializer],\n ['new_owner_authority', AuthoritySerializer]\n])\n\nOperationSerializers.set_reset_account = OperationDataSerializer(OPERATION_IDS.set_reset_account, [\n ['account', StringSerializer],\n ['current_reset_account', StringSerializer],\n ['reset_account', StringSerializer]\n])\n\nOperationSerializers.set_withdraw_vesting_route = OperationDataSerializer(\n OPERATION_IDS.set_withdraw_vesting_route,\n [\n ['from_account', StringSerializer],\n ['to_account', StringSerializer],\n ['percent', UInt16Serializer],\n ['auto_vest', BooleanSerializer]\n ]\n)\n\nOperationSerializers.transfer = OperationDataSerializer(OPERATION_IDS.transfer, [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n])\n\nOperationSerializers.transfer_from_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_from_savings,\n [\n ['from', StringSerializer],\n ['request_id', UInt32Serializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_savings = OperationDataSerializer(\n OPERATION_IDS.transfer_to_savings,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer]\n ]\n)\n\nOperationSerializers.transfer_to_vesting = OperationDataSerializer(\n OPERATION_IDS.transfer_to_vesting,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.vote = OperationDataSerializer(OPERATION_IDS.vote, [\n ['voter', StringSerializer],\n ['author', StringSerializer],\n ['permlink', StringSerializer],\n ['weight', Int16Serializer]\n])\n\nOperationSerializers.withdraw_vesting = OperationDataSerializer(OPERATION_IDS.withdraw_vesting, [\n ['account', StringSerializer],\n ['vesting_shares', AssetSerializer]\n])\n\nOperationSerializers.witness_update = OperationDataSerializer(OPERATION_IDS.witness_update, [\n ['owner', StringSerializer],\n ['url', StringSerializer],\n ['block_signing_key', PublicKeySerializer],\n ['props', ChainPropertiesSerializer],\n ['fee', AssetSerializer]\n])\n\nOperationSerializers.witness_set_properties = OperationDataSerializer(\n OPERATION_IDS.witness_set_properties,\n [\n ['owner', StringSerializer],\n ['props', FlatMapSerializer(StringSerializer, VariableBinarySerializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.account_update2 = OperationDataSerializer(OPERATION_IDS.account_update2, [\n ['account', StringSerializer],\n ['owner', OptionalSerializer(AuthoritySerializer)],\n ['active', OptionalSerializer(AuthoritySerializer)],\n ['posting', OptionalSerializer(AuthoritySerializer)],\n ['memo_key', OptionalSerializer(PublicKeySerializer)],\n ['json_metadata', StringSerializer],\n ['posting_json_metadata', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.create_proposal = OperationDataSerializer(OPERATION_IDS.create_proposal, [\n ['creator', StringSerializer],\n ['receiver', StringSerializer],\n ['start_date', DateSerializer],\n ['end_date', DateSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nOperationSerializers.update_proposal_votes = OperationDataSerializer(\n OPERATION_IDS.update_proposal_votes,\n [\n ['voter', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['approve', BooleanSerializer],\n ['extensions', ArraySerializer(VoidSerializer)]\n ]\n)\n\nOperationSerializers.remove_proposal = OperationDataSerializer(OPERATION_IDS.remove_proposal, [\n ['proposal_owner', StringSerializer],\n ['proposal_ids', ArraySerializer(Int64Serializer)],\n ['extensions', ArraySerializer(VoidSerializer)]\n])\n\nconst ProposalUpdateSerializer = ObjectSerializer([['end_date', DateSerializer]])\n\nOperationSerializers.update_proposal = OperationDataSerializer(OPERATION_IDS.update_proposal, [\n ['proposal_id', UInt64Serializer],\n ['creator', StringSerializer],\n ['daily_pay', AssetSerializer],\n ['subject', StringSerializer],\n ['permlink', StringSerializer],\n [\n 'extensions',\n ArraySerializer(StaticVariantSerializer([VoidSerializer, ProposalUpdateSerializer]))\n ]\n])\n\nOperationSerializers.collateralized_convert = OperationDataSerializer(\n OPERATION_IDS.collateralized_convert,\n [\n ['owner', StringSerializer],\n ['requestid', UInt32Serializer],\n ['amount', AssetSerializer]\n ]\n)\n\nOperationSerializers.recurrent_transfer = OperationDataSerializer(\n OPERATION_IDS.recurrent_transfer,\n [\n ['from', StringSerializer],\n ['to', StringSerializer],\n ['amount', AssetSerializer],\n ['memo', StringSerializer],\n ['recurrence', UInt16Serializer],\n ['executions', UInt16Serializer],\n [\n 'extensions',\n ArraySerializer(\n ObjectSerializer([\n ['type', UInt8Serializer],\n ['value', ObjectSerializer([['pair_id', UInt8Serializer]])]\n ])\n )\n ]\n ]\n)\n\nconst OperationSerializer = (buffer: ByteBuffer, operation: Operation) => {\n const serializer = OperationSerializers[operation[0]]\n if (!serializer) {\n throw new Error(`No serializer for operation: ${operation[0]}`)\n }\n try {\n serializer(buffer, operation[1])\n } catch (error: any) {\n error.message = `${operation[0]}: ${error.message}`\n throw error\n }\n}\n\nconst TransactionSerializer = ObjectSerializer([\n ['ref_block_num', UInt16Serializer],\n ['ref_block_prefix', UInt32Serializer],\n ['expiration', DateSerializer],\n ['operations', ArraySerializer(OperationSerializer)],\n ['extensions', ArraySerializer(StringSerializer)]\n])\n\nconst EncryptedMemoSerializer = ObjectSerializer([\n ['from', PublicKeySerializer],\n ['to', PublicKeySerializer],\n ['nonce', UInt64Serializer],\n ['check', UInt32Serializer],\n ['encrypted', BinarySerializer()]\n])\n\nexport const Serializer = {\n // Array: ArraySerializer,\n Asset: AssetSerializer,\n // Authority: AuthoritySerializer,\n // Binary: BinarySerializer,\n // Boolean: BooleanSerializer,\n // Date: DateSerializer,\n // FlatMap: FlatMapSerializer,\n // Int16: Int16Serializer,\n // Int32: Int32Serializer,\n // Int64: Int64Serializer,\n // Int8: Int8Serializer,\n Memo: EncryptedMemoSerializer,\n // Object: ObjectSerializer,\n // Operation: OperationSerializer,\n // Optional: OptionalSerializer,\n Price: PriceSerializer,\n PublicKey: PublicKeySerializer,\n // StaticVariant: StaticVariantSerializer,\n String: StringSerializer,\n Transaction: TransactionSerializer,\n UInt16: UInt16Serializer,\n UInt32: UInt32Serializer\n // UInt64: UInt64Serializer,\n // UInt8: UInt8Serializer,\n // Void: VoidSerializer\n}\n","export const sleep = (ms: number): Promise => {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { config } from '../config'\nimport { CallResponse } from '../types'\nimport type { APIMethods } from '../api-types'\nimport { sleep } from './sleep'\n\n// ── Server identity (User-Agent) ────────────────────────────────────────────\n\n/**\n * True only when running under Node.js (SSR / server / CLI). Computed once.\n *\n * We attach a descriptive `User-Agent` exclusively here because that is the only\n * place it (a) takes effect and (b) is wanted:\n * - Node's undici fetch otherwise sends a bare `User-Agent: node`, which is\n * indistinguishable from any anonymous script in node/CDN analytics.\n * - Browsers treat `User-Agent` as a forbidden header and silently drop any\n * override, so setting it there is pointless (and we avoid the churn).\n * - React Native sets its own native UA (e.g. the mobile app's own string);\n * overriding it would relabel real mobile traffic, so we explicitly exclude\n * it via `navigator.product === 'ReactNative'`.\n */\nconst isNodeRuntime: boolean = (() => {\n try {\n const isReactNative =\n typeof navigator !== 'undefined' && (navigator as any).product === 'ReactNative'\n return (\n !isReactNative &&\n typeof process !== 'undefined' &&\n process.versions != null &&\n process.versions.node != null\n )\n } catch {\n return false\n }\n})()\n\n/**\n * Headers that identify the caller on server-side requests. Returns the\n * configured `User-Agent` only under Node; an empty object everywhere else so\n * browser and React Native requests are left exactly as they were.\n */\nfunction serverIdentityHeaders(): Record {\n return isNodeRuntime ? { 'User-Agent': config.userAgent } : {}\n}\n\n// ── Error Types ─────────────────────────────────────────────────────────────\n\nexport class RPCError extends Error {\n name = 'RPCError'\n data?: any\n code: number\n stack: undefined = undefined\n constructor(rpcError: { message: string; code: number; data?: any }) {\n super(rpcError.message)\n this.code = rpcError.code\n if ('data' in rpcError) {\n this.data = rpcError.data\n }\n }\n}\n\n/**\n * Transport-level error thrown by jsonRPCCall for HTTP status errors (429, 503).\n * Carries node identity and rate-limit info so callers can record health\n * exactly once without double-counting.\n */\nclass NodeError extends Error {\n node: string\n /** Explicit server `Retry-After` in ms, or 0 when the 429 carried no usable header. */\n rateLimitMs: number\n /** True for an HTTP 429 regardless of whether a `Retry-After` header was present, so\n * a header-less rate limit is still cooled down (with escalating backoff) rather than\n * mis-recorded as a plain transport failure. */\n isRateLimit: boolean\n constructor(\n node: string,\n message: string,\n opts: { rateLimitMs?: number; isRateLimit?: boolean } = {}\n ) {\n super(message)\n this.node = node\n this.rateLimitMs = opts.rateLimitMs ?? 0\n this.isRateLimit = opts.isRateLimit ?? false\n }\n}\n\n/**\n * Parse an HTTP `Retry-After` header to milliseconds. Supports both forms in the\n * spec: `` (e.g. \"120\") and ``. Returns 0 when the header\n * is absent or unparseable (including a non-numeric junk value or a past date) so the\n * caller falls back to escalating backoff instead of a NaN/negative cooldown.\n */\nfunction parseRetryAfterMs(header: string | null): number {\n if (!header) return 0\n const secs = Number(header)\n if (Number.isFinite(secs)) return secs > 0 ? secs * 1000 : 0\n const dateMs = Date.parse(header)\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now()\n return delta > 0 ? delta : 0\n }\n return 0\n}\n\n/** Errors that indicate the request definitely never reached the server. */\nconst PRE_CONNECTION_ERRORS = ['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']\n\n/** Browser fetch network-failure messages — emitted by Chromium/Firefox/Safari\n * when CORS preflight fails, DNS fails, TLS fails, or the response is blocked.\n * These map to scenarios where retrying the same signed broadcast is safe: the\n * request either never reached the node, or its response was blocked but a\n * re-broadcast of the *same* signed tx will be deduped by Hive (same trx_id). */\nconst BROWSER_NETWORK_ERRORS = [\n 'Failed to fetch', // Chromium\n 'NetworkError when attempting to fetch', // Firefox\n 'Load failed', // Safari\n 'fetch failed' // Node 18+ undici / Bun — also covered via cause chain\n]\n\n/**\n * Concatenate the error's surface text + the messages/codes from up to 5\n * levels of nested `cause`. Node.js fetch wraps connection failures as\n * `TypeError('fetch failed')` with the real `code` (ECONNREFUSED, etc.)\n * nested in the cause chain. Browser fetch failures have no cause but\n * carry their identifier in `message`.\n */\nfunction flattenErrorText(e: any): string {\n if (!e) return ''\n const parts: string[] = [String(e.name || ''), String(e.message || ''), String(e.code || '')]\n let cause = e.cause\n for (let depth = 0; cause && depth < 5; depth++) {\n parts.push(String(cause.code || ''), String(cause.message || ''))\n cause = cause.cause\n }\n return parts.join(' ')\n}\n\n/**\n * Decide whether a broadcast attempt can safely be retried on another node.\n *\n * Safe to retry (same signed tx → Hive dedupes by trx_id at the mempool layer):\n * - Pre-connection failures (ECONNREFUSED, ENOTFOUND, etc.) — request never sent.\n * - Browser fetch network failures (CORS block, TLS error, DNS) — TypeError with\n * a well-known message string.\n * - JSON parse failures — node returned an HTML error page (typical for\n * Cloudflare 1033 tunnel-down / 5xx interstitials), so the request never\n * reached the Hive RPC layer.\n * - NodeError (HTTP 429/5xx surfaced from jsonRPCCall) — already known transient.\n *\n * NOT safe to retry:\n * - RPCError — the node accepted the request and the blockchain rejected it.\n * Retrying on another node would either get the same rejection or accept\n * a different one; surface the original error instead.\n */\nfunction isBroadcastSafeToRetry(e: any): boolean {\n if (!e) return false\n if (e instanceof NodeError) return true\n if (e instanceof RPCError) return false\n\n const text = flattenErrorText(e)\n if (PRE_CONNECTION_ERRORS.some((code) => text.includes(code))) return true\n if (BROWSER_NETWORK_ERRORS.some((msg) => text.includes(msg))) return true\n\n // res.json() against an HTML body (Cloudflare/proxy interstitials) throws\n // SyntaxError. The Hive RPC layer never saw the tx, so failover is safe.\n if (e instanceof SyntaxError) return true\n // Some runtimes surface JSON parse errors as plain Error with this text.\n if (/Unexpected token|JSON\\.parse|Unexpected end of JSON/i.test(text)) return true\n\n return false\n}\n\n// ── Node Health Tracker ─────────────────────────────────────────────────────\n\n/** Node-level health state tracked by NodeHealthTracker. */\ninterface NodeHealth {\n /** Global consecutive-failure counter. Resets on success. */\n consecutiveFailures: number\n /** Timestamp of the most recent failure. Used with the 30s cooldown window. */\n lastFailureTime: number\n /** Epoch ms after which the node is no longer rate-limited. */\n rateLimitedUntil: number\n /** Count of consecutive 429s (no intervening success) with no usable Retry-After.\n * Drives escalating backoff; reset by a success or by RATE_LIMIT_STREAK_RESET_MS. */\n rateLimitStreak: number\n /** Epoch ms of the most recent 429. Used to expire the escalation streak. */\n lastRateLimitAt: number\n /** Per-API failure counters. Some nodes disable specific API plugins; tracking\n * per-API lets us deprioritize a node only for the APIs that fail, not globally.\n * `defective` marks a cooldown set by recordDefectiveResponse (payload\n * validation failure) — unlike ordinary strike cooldowns it survives\n * recordSuccess and only expires on its own. */\n apiFailures: Map<\n string,\n { count: number; cooldownUntil: number; lastFailureTime: number; defective?: boolean }\n >\n /** Most recent head_block_number observed for this node. */\n headBlock: number\n /** Epoch ms when the head_block was recorded. Used to expire stale observations. */\n headBlockUpdatedAt: number\n\n // ── Latency tracking (adaptive ordering) ────────────────────────────────\n /** EWMA of observed round-trip ms. Fed by successful calls AND by slow/timeout\n * failures (so a node that returns 200 in 15s, or aborts at the timeout, is\n * ranked on its real slowness — not treated as merely \"healthy\"). `undefined`\n * until the first sample. */\n ewmaLatencyMs?: number\n /** Number of latency samples folded into the EWMA. Gates \"warmup\": below\n * LATENCY_MIN_SAMPLES the node is unproven and keeps its config-order prior. */\n latencySampleCount: number\n /** Epoch ms of the most recent latency sample. Used for usability expiry and to\n * decide when a node is overdue for an exploratory re-probe. */\n latencyUpdatedAt: number\n /** Epoch ms of the most recent exploratory promotion. Single-flight guard so a\n * burst of concurrent orderings doesn't all re-probe the same stale node. */\n lastProbeAt: number\n\n /**\n * Per-profile-key latency (same EWMA/warmup/expiry rules as the global one).\n * The global EWMA mixes cheap calls (get_accounts ~300ms) with heavy ones\n * (get_account_history, bridge.get_discussion — legitimately seconds), so it\n * ranks nodes fine but is the WRONG baseline for per-attempt deadlines: a\n * profile dominated by cheap calls would abort every legitimately-heavy call.\n * Deadlines/hedge delays therefore key on the FULL method for RPC\n * (\"condenser_api.get_account_history\") and api+endpoint template for REST —\n * an API prefix alone still mixes cheap and heavy methods. Ranking keeps the\n * global profile. Bounded: #nodes × #distinct methods called (code-defined,\n * not user input); fully cleared whenever the node's global profile expires\n * (the global clock advances on every sample, so global-stale ⇒ all stale).\n */\n apiLatency: Map\n}\n\n/**\n * JSON-RPC error codes that indicate the node itself is unhealthy, not that the\n * client sent a bad request. These should trigger failover to another node.\n *\n * Background: Hive nodes fronted by HAF/jussi/drone return HTTP 200 with a\n * JSON-RPC error body when a backing service (hivemind, postgrest, etc.) is down.\n * The HTTP layer looks healthy, so failover never triggers — the caller just gets\n * an error and gives up. This function identifies those node-level errors.\n */\nfunction isNodeLevelRPCError(code: number, message: string): boolean {\n // -32603: Internal error — node is having problems\n if (code === -32603) return true\n // -32000 to -32099: Server error range (implementation-defined server errors)\n if (code <= -32000 && code >= -32099) return true\n // -32601: Method not found — node may be missing this API plugin\n if (code === -32601) return true\n // -32602 with node-sick indicators (vs normal \"invalid params\" from bad client input)\n // e.g. \"Unable to parse endpoint data\" from HAF when a backing service is down\n if (code === -32602 && /unable to parse|endpoint data|internal/i.test(message)) return true\n return false\n}\n\n/** Extract the API prefix from a method name like \"rc_api.find_rc_accounts\" -> \"rc_api\". */\nfunction apiOf(method: string): string {\n const dot = method.indexOf('.')\n return dot > 0 ? method.slice(0, dot) : method\n}\n\n// ── Rate-limit (429) backoff constants ───────────────────────────────────────\n/** Base cooldown applied to a 429 with no usable `Retry-After` header. Matches the\n * previous flat default so first-offence behaviour is unchanged. */\nconst RATE_LIMIT_BASE_MS = 10_000\n/** Ceiling for the escalating header-less cooldown. Prevents a node from being\n * parked far longer than a real public node's throttle window. */\nconst RATE_LIMIT_MAX_MS = 60_000\n/** No 429 from a node for this long ⇒ its escalation streak resets to 0, so an\n * occasional throttle hours apart doesn't compound into a long park. */\nconst RATE_LIMIT_STREAK_RESET_MS = 120_000\n\n/** Per-API failure threshold before the node is deprioritized for that API only. */\nconst MAX_API_FAILURES_BEFORE_COOLDOWN = 2\n/** How long a node stays deprioritized for a specific API after repeated failures. */\nconst API_COOLDOWN_MS = 60_000\n/** How long head_block observations remain valid before being treated as unknown. */\nconst HEAD_BLOCK_MAX_AGE_MS = 120_000\n/** Maximum lag (in blocks) before a node is considered stale relative to the best-known head. */\nconst STALE_BLOCK_THRESHOLD = 30\n\n// ── Adaptive latency-ordering constants ──────────────────────────────────────\n/** EWMA smoothing weight for a new latency sample. 0.3 ⇒ ~5–6 samples to converge;\n * absorbs one-off GC/TLS spikes while still reacting to a real regional shift fast. */\nconst LATENCY_EWMA_ALPHA = 0.3\n/** Samples required before a node's latency is trusted for ranking. Below this the\n * node is \"warming\" and ranks at a neutral prior (config order via tiebreak), so a\n * single fluke never reorders the list and cold start == today's behavior. */\nconst LATENCY_MIN_SAMPLES = 3\n/** How long a latency sample stays usable for ranking. Past this a node reverts to\n * warming. Must be > LATENCY_REPROBE_MS so re-probes keep a busy node's profile fresh. */\nconst LATENCY_MAX_AGE_MS = 5 * 60_000\n/** A healthy node not sampled within this window is overdue for an exploratory\n * re-probe (promoted to front of ONE ordering). This is what lets a demoted node\n * climb back when it recovers — and what profiles a node that organic traffic never\n * reaches. 60s ⇒ ~1 probe/node/min worst case = negligible cost. */\nconst LATENCY_REPROBE_MS = 60_000\n/** Neutral score (ms) for an unproven/warming node: optimistic enough to sit ahead\n * of a proven-slow node (so we explore an unknown before hammering a known-slow one)\n * but behind a proven-fast node. Fixed, so a node makes at most ONE rank transition\n * when it crosses LATENCY_MIN_SAMPLES — no churn. */\nconst LATENCY_UNPROVEN_PRIOR_MS = 1_000\n/** A failed call only feeds a latency penalty if it was actually slow (≥ this). Keeps\n * a genuine timeout / slow-5xx (a far-region node case) visible to the ranker while an\n * instant ECONNREFUSED (a *down* node, handled by consecutiveFailures) is NOT mis-read\n * as \"slow\". The penalty value is the *measured* elapsed, never a static constant. */\nconst LATENCY_SLOW_FAILURE_MS = 2_000\n\n/**\n * Latency-ranking tuning, re-exported as a frozen bag so tests assert behaviour\n * against the real numbers instead of mirroring literals that can silently drift.\n * @internal — not part of the package's public API; for the co-located spec only.\n */\nexport const __LATENCY_TUNING__ = Object.freeze({\n EWMA_ALPHA: LATENCY_EWMA_ALPHA,\n MIN_SAMPLES: LATENCY_MIN_SAMPLES,\n MAX_AGE_MS: LATENCY_MAX_AGE_MS,\n REPROBE_MS: LATENCY_REPROBE_MS,\n UNPROVEN_PRIOR_MS: LATENCY_UNPROVEN_PRIOR_MS,\n SLOW_FAILURE_MS: LATENCY_SLOW_FAILURE_MS\n})\n\n/** @internal Exported for testing only. */\nexport class NodeHealthTracker {\n private health = new Map()\n\n private getOrCreate(node: string): NodeHealth {\n let h = this.health.get(node)\n if (!h) {\n h = {\n consecutiveFailures: 0,\n lastFailureTime: 0,\n rateLimitedUntil: 0,\n rateLimitStreak: 0,\n lastRateLimitAt: 0,\n apiFailures: new Map(),\n headBlock: 0,\n headBlockUpdatedAt: 0,\n ewmaLatencyMs: undefined,\n latencySampleCount: 0,\n latencyUpdatedAt: 0,\n // Stamp the probe clock at creation so a brand-new (never-sampled) node is\n // NOT treated as \"overdue for re-probe\" on its very first ordering pass.\n // With lastProbeAt=0 the re-probe gate (touch <= now - LATENCY_REPROBE_MS)\n // fired immediately, so the 2nd+ ordering on a cold worker promoted unproven\n // nodes ahead of the configured order for no measured reason. Seeding it to\n // \"now\" preserves configured order during warmup; a genuinely slow preferred\n // node is still demoted by its EWMA score (not by epoch-zero exploration),\n // and idle nodes are still re-probed once LATENCY_REPROBE_MS has truly elapsed.\n lastProbeAt: Date.now(),\n apiLatency: new Map()\n }\n this.health.set(node, h)\n }\n return h\n }\n\n recordSuccess(node: string, api?: string, durationMs?: number, profileKey?: string): void {\n const h = this.getOrCreate(node)\n h.consecutiveFailures = 0\n // A success means the node recovered — clear the escalation streak so the next\n // throttle starts from the base cooldown. We deliberately do NOT clear an active\n // rateLimitedUntil window here: under concurrency a success from a request that was\n // already in flight can resolve *after* another request recorded a fresh 429\n // Retry-After, and erasing the window would put a just-throttled node back into\n // rotation early. The window expires on its own (short for header-less; the server's\n // value for an explicit Retry-After).\n h.rateLimitStreak = 0\n if (api) {\n // A successful API call clears that API's failure counter — but never an\n // ACTIVE defective-response cooldown: the \"success\" may itself be an\n // unvalidated read from the same lying node (validated calls are the\n // minority of traffic), and re-admitting it early defeats the decisive\n // penalty. That window expires on its own, like rateLimitedUntil above.\n const apiFail = h.apiFailures.get(api)\n if (!apiFail || !(apiFail.defective && apiFail.cooldownUntil > Date.now())) {\n h.apiFailures.delete(api)\n }\n }\n if (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0) {\n // Latency profiles use the finest key available (full method / endpoint\n // template); the API prefix is only a fallback so bare callers still\n // profile SOMETHING. Failure state above stays per-API on purpose.\n this.recordLatency(h, durationMs, profileKey ?? api)\n }\n }\n\n /**\n * Record a *slow* failed call as a latency signal. The failure counters are\n * updated separately (recordFailure/recordError); this only feeds the EWMA so a\n * node that returns 200-but-too-slow, times out, or returns a slow 5xx is ranked\n * on its real slowness. Callers pass the MEASURED elapsed ms and only call this\n * when the call was genuinely slow (≥ LATENCY_SLOW_FAILURE_MS) — an instant\n * connection failure (a *down* node) must NOT look \"slow\".\n */\n recordSlowFailure(node: string, durationMs: number, profileKey?: string): void {\n if (!Number.isFinite(durationMs) || durationMs < LATENCY_SLOW_FAILURE_MS) return\n this.recordLatency(this.getOrCreate(node), durationMs, profileKey)\n }\n\n /**\n * Usable latency profile (EWMA ms), or `undefined` while unproven or stale.\n * With a `profileKey` (full RPC method / REST api+endpoint template),\n * returns that (node, key) profile ONLY — deliberately no fallback to the\n * mixed global profile, because an average dominated by cheap calls is the\n * wrong deadline baseline for a heavy method (that fallback is exactly the\n * \"2s window starves get_account_history\" failure mode). Without a key,\n * returns the global ranking profile. Both follow the same \"profiled and\n * fresh\" gate as the ranker.\n * @internal\n */\n getUsableLatencyMs(node: string, profileKey?: string): number | undefined {\n const h = this.health.get(node)\n if (!h) return undefined\n const now = Date.now()\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n return p &&\n p.sampleCount >= LATENCY_MIN_SAMPLES &&\n now - p.updatedAt <= LATENCY_MAX_AGE_MS\n ? p.ewmaMs\n : undefined\n }\n return this.isLatencyUsable(h, now) ? h.ewmaLatencyMs : undefined\n }\n\n /**\n * Censored latency sample for a request that was ABORTED because a hedge\n * completed first while it was still in flight. The elapsed-at-abort is a\n * *lower bound* on the true latency, so folding it in can only move the\n * node's EWMA toward the truth, never below it — which is what lets repeated\n * hedge-wins reorder the pool. Deliberately does NOT touch the failure\n * counters or rate-limit state: the node returned no error, it was merely\n * slow, and treating cancellation as failure would flap `isNodeHealthy`.\n * Callers must NOT record this for a primary that already settled on its own\n * (its outcome was recorded normally; a second sample would be fabricated).\n * Bypasses the `recordSlowFailure` 2s floor (a hedge can win well below it).\n * By construction the elapsed is ≥ the hedge delay, so only a degenerate\n * near-zero epsilon needs rejecting — anything under one LAN round trip is\n * noise, not a latency measurement.\n * @internal\n */\n recordCensoredLatency(node: string, elapsedMs: number, profileKey?: string): void {\n if (!Number.isFinite(elapsedMs) || elapsedMs < 50) return\n this.recordLatency(this.getOrCreate(node), elapsedMs, profileKey)\n }\n\n /**\n * Fold a latency sample into the node's global EWMA (warmup + usability\n * bookkeeping) and, when a profile key is given, into that (node, key)\n * profile — the global one ranks nodes, the keyed one calibrates deadlines.\n */\n private recordLatency(h: NodeHealth, durationMs: number, profileKey?: string): void {\n const now = Date.now()\n // A profile older than the usable window starts fresh, so an idled process\n // re-learns from scratch rather than ranking on hour-old data. Every keyed\n // profile shares this clock (each sample updates both), so global-stale\n // implies every keyed profile is stale too — clear the map rather than\n // leave never-again-read tombstone entries for the life of the process.\n if (h.latencyUpdatedAt > 0 && now - h.latencyUpdatedAt > LATENCY_MAX_AGE_MS) {\n h.ewmaLatencyMs = undefined\n h.latencySampleCount = 0\n h.apiLatency.clear()\n }\n h.ewmaLatencyMs =\n h.ewmaLatencyMs === undefined\n ? durationMs\n : LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * h.ewmaLatencyMs\n h.latencySampleCount++\n h.latencyUpdatedAt = now\n\n if (profileKey !== undefined) {\n const p = h.apiLatency.get(profileKey)\n if (!p || now - p.updatedAt > LATENCY_MAX_AGE_MS) {\n h.apiLatency.set(profileKey, { ewmaMs: durationMs, sampleCount: 1, updatedAt: now })\n } else {\n p.ewmaMs = LATENCY_EWMA_ALPHA * durationMs + (1 - LATENCY_EWMA_ALPHA) * p.ewmaMs\n p.sampleCount++\n p.updatedAt = now\n }\n }\n }\n\n recordFailure(node: string, api?: string): void {\n const h = this.getOrCreate(node)\n if (api) {\n // API-specific failure: only update the per-API tracker.\n // This prevents e.g. 3 rc_api failures from marking the node\n // globally unhealthy for condenser_api too.\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n // Reset counter if previous cooldown expired OR last failure was >30s ago\n // (avoids sticky penalties from sparse failures hours apart)\n if (\n (existing.cooldownUntil > 0 && existing.cooldownUntil <= now) ||\n (existing.lastFailureTime > 0 && now - existing.lastFailureTime > 30_000)\n ) {\n existing.count = 0\n existing.cooldownUntil = 0\n }\n existing.count++\n existing.lastFailureTime = now\n if (existing.count >= MAX_API_FAILURES_BEFORE_COOLDOWN) {\n existing.cooldownUntil = now + API_COOLDOWN_MS\n }\n h.apiFailures.set(api, existing)\n } else {\n // Transport-level failure (no specific API): update global counter\n h.consecutiveFailures++\n h.lastFailureTime = Date.now()\n }\n }\n\n /**\n * A response that failed the caller's payload validation is a decisive,\n * reproducible node fault — the node answered 200 with data the caller KNOWS\n * to be impossible — so it trips the per-API cooldown immediately instead of\n * accruing ordinary strikes. Deliberately its own method rather than\n * recordFailure × N: ordinary strikes are cleared by any success, and a\n * top-ranked lying node keeps recording successes on the unvalidated calls\n * between probes, which would reset its strikes forever and keep it in\n * rotation (observed live). Scope stays per-API: the node may be perfectly\n * healthy for its other API families.\n */\n recordDefectiveResponse(node: string, api: string): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n const existing: {\n count: number\n cooldownUntil: number\n lastFailureTime: number\n defective?: boolean\n } = h.apiFailures.get(api) ?? { count: 0, cooldownUntil: 0, lastFailureTime: 0 }\n existing.count = Math.max(existing.count + 1, MAX_API_FAILURES_BEFORE_COOLDOWN)\n existing.lastFailureTime = now\n existing.cooldownUntil = now + API_COOLDOWN_MS\n existing.defective = true\n h.apiFailures.set(api, existing)\n }\n\n /**\n * Cool down a rate-limited node. Honors an explicit server `Retry-After`\n * (`retryAfterMs`) exactly — the server told us when to return. With no usable\n * header, applies escalating backoff: BASE, 2×BASE, 4×BASE … capped at\n * RATE_LIMIT_MAX_MS, indexed by the node's consecutive-429 streak (reset by a\n * success or after RATE_LIMIT_STREAK_RESET_MS of quiet). This stops a throttled\n * public node from being re-admitted every 10s and re-hammered under sustained\n * load, which matters most when the fleet's own unlimited node is removed.\n */\n recordRateLimit(node: string, retryAfterMs?: number): void {\n const h = this.getOrCreate(node)\n const now = Date.now()\n // Expire a stale streak so an occasional throttle hours apart doesn't compound.\n if (h.rateLimitStreak > 0 && now - h.lastRateLimitAt > RATE_LIMIT_STREAK_RESET_MS) {\n h.rateLimitStreak = 0\n }\n const hasHeader = typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0\n const cooldown = hasHeader\n ? retryAfterMs!\n : Math.min(RATE_LIMIT_BASE_MS * 2 ** h.rateLimitStreak, RATE_LIMIT_MAX_MS)\n // Only a header-less 429 advances the escalation streak — an explicit Retry-After is\n // honored exactly and must not compound the header-less backoff (else several\n // Retry-After 429s would push a later header-less 429 straight to the 60s cap).\n if (!hasHeader) h.rateLimitStreak++\n h.lastRateLimitAt = now\n // Explicit Retry-After is honored exactly (the server's current instruction). A\n // header-less cooldown may only move the window FORWARD — it must never truncate a\n // longer window already set, e.g. a node parked for an hour by an explicit\n // Retry-After that is later retried as a last resort and returns a header-less 429\n // must not have its 1h window cut down to the 10s base.\n h.rateLimitedUntil = hasHeader\n ? now + cooldown\n : Math.max(h.rateLimitedUntil, now + cooldown)\n h.consecutiveFailures++\n h.lastFailureTime = now\n }\n\n /** Record an observed head_block_number for this node. */\n recordHeadBlock(node: string, blockNum: number): void {\n if (!blockNum || !Number.isFinite(blockNum)) return\n const h = this.getOrCreate(node)\n h.headBlock = blockNum\n h.headBlockUpdatedAt = Date.now()\n }\n\n /**\n * Consensus head block from recent observations. Uses the median rather than the\n * max to prevent a single bad/misconfigured node from poisoning the reference.\n * A node reporting an inflated head_block won't affect the median unless the\n * majority of nodes agree on that range.\n */\n private consensusHeadBlock(): number {\n const now = Date.now()\n const recent: number[] = []\n for (const h of this.health.values()) {\n if (h.headBlock > 0 && now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS) {\n recent.push(h.headBlock)\n }\n }\n if (recent.length < 2) return 0 // Need at least 2 observations to compare\n recent.sort((a, b) => a - b)\n // Median: for even length, use the lower-middle value (conservative)\n return recent[Math.floor((recent.length - 1) / 2)]\n }\n\n /** True if this node is healthy (globally and for the given API if provided). */\n isNodeHealthy(node: string, api?: string): boolean {\n const h = this.health.get(node)\n if (!h) return true // unknown nodes assumed healthy\n const now = Date.now()\n\n // Rate-limited and cooldown hasn't expired\n if (h.rateLimitedUntil > now) return false\n\n // Too many consecutive failures within the last 30 seconds\n if (h.consecutiveFailures >= 3 && now - h.lastFailureTime < 30_000) return false\n\n // Per-API cooldown: node may be healthy overall but missing this API plugin\n if (api) {\n const apiFail = h.apiFailures.get(api)\n if (apiFail && apiFail.cooldownUntil > now) return false\n }\n\n // Head-block staleness: deprioritize nodes lagging behind the consensus head\n const best = this.consensusHeadBlock()\n if (\n best > 0 &&\n h.headBlock > 0 &&\n now - h.headBlockUpdatedAt <= HEAD_BLOCK_MAX_AGE_MS &&\n best - h.headBlock > STALE_BLOCK_THRESHOLD\n ) {\n return false\n }\n\n return true\n }\n\n /**\n * Order nodes best-first: healthy nodes sorted by adaptive latency score, then\n * unhealthy nodes appended. Capability / staleness / rate-limit filtering stays in\n * `isNodeHealthy` and is unchanged — latency only reorders WITHIN the healthy set,\n * and only WITHIN the array it is handed (so it never leaves the configured list).\n *\n * One ordering per pass MAY promote a healthy node overdue for a re-probe (never\n * sampled, or not sampled within LATENCY_REPROBE_MS) to the front — single-flight\n * via `lastProbeAt`. This is what lets a demoted node climb back when it recovers,\n * and profiles a node that organic traffic (always served by a faster peer) never\n * reaches. Cold start: with no profiles, every node scores the neutral prior and the\n * stable config-index tiebreak yields the original order — i.e. today's behavior.\n */\n getOrderedNodes(nodes: string[], api?: string): string[] {\n const healthy: string[] = []\n const unhealthy: string[] = []\n for (const node of nodes) {\n if (this.isNodeHealthy(node, api)) {\n healthy.push(node)\n } else {\n unhealthy.push(node)\n }\n }\n if (healthy.length <= 1) {\n return [...healthy, ...unhealthy]\n }\n const now = Date.now()\n // Every score in THIS pass falls back to config index on ties → a total,\n // transitive order with no memo (so no stale-denominator inversions).\n const ordered = healthy\n .map((node, i) => ({ node, i, score: this.scoreNode(node, now) }))\n .sort((a, b) => a.score - b.score || a.i - b.i)\n .map((d) => d.node)\n const probe = this.pickReprobeCandidate(healthy, now)\n if (probe && ordered[0] !== probe) {\n return [probe, ...ordered.filter((n) => n !== probe), ...unhealthy]\n }\n return [...ordered, ...unhealthy]\n }\n\n /** A node's latency is usable for ranking only if profiled (≥ MIN_SAMPLES) and fresh. */\n private isLatencyUsable(h: NodeHealth | undefined, now: number): boolean {\n return (\n !!h &&\n h.ewmaLatencyMs !== undefined &&\n h.latencySampleCount >= LATENCY_MIN_SAMPLES &&\n now - h.latencyUpdatedAt <= LATENCY_MAX_AGE_MS\n )\n }\n\n /**\n * Ranking score (lower = better). Unproven/warming nodes get a fixed neutral prior\n * so they sit ahead of a proven-slow node but behind a proven-fast one, and make at\n * most one rank transition when they cross MIN_SAMPLES (no churn).\n */\n private scoreNode(node: string, now: number): number {\n const h = this.health.get(node)\n if (!this.isLatencyUsable(h, now)) return LATENCY_UNPROVEN_PRIOR_MS\n return h!.ewmaLatencyMs!\n }\n\n /**\n * At most one healthy node overdue for an exploratory re-probe: never sampled, or\n * neither sampled nor re-probed within LATENCY_REPROBE_MS. Returns the stalest such\n * node and stamps `lastProbeAt` to single-flight it against concurrent orderings.\n *\n * Note: `getOrCreate` here materializes a health entry per node in the passed list.\n * The node list (`config.nodes`/`restNodes`) is treated as effectively static — set\n * once via `setNodes` — so the map is bounded. If a host is ever removed from the\n * list at runtime its stale entry is simply ignored (never re-surfaced) and is a\n * negligible, bounded amount of memory.\n */\n private pickReprobeCandidate(healthy: string[], now: number): string | undefined {\n const threshold = now - LATENCY_REPROBE_MS\n let cand: string | undefined\n let candTouch = Infinity\n for (const n of healthy) {\n const h = this.getOrCreate(n)\n const touch = Math.max(h.latencyUpdatedAt, h.lastProbeAt)\n if (touch <= threshold && touch < candTouch) {\n cand = n\n candTouch = touch\n }\n }\n if (cand) this.getOrCreate(cand).lastProbeAt = now\n return cand\n }\n}\n\n// Exported for the co-located specs only (asserting the call sites' effect on\n// health). Not re-exported by hive-tx/index.ts, so NOT part of the public API.\n// @internal\nexport const rpcHealthTracker = new NodeHealthTracker()\n// @internal\nexport const restHealthTracker = new NodeHealthTracker()\n\n// ── Hedged-request budget ────────────────────────────────────────────────────\n\n/**\n * Token bucket bounding hedged (duplicated) read requests to a fraction of\n * overall traffic. A hedge spends 1 token; every un-hedged success refills\n * `config.resilience.hedgeRefillPerSuccess` (default 0.1 ⇒ steady-state hedge\n * rate ≤ ~9% of successful traffic, with bursts up to `hedgeBucketCapacity`).\n * The self-limiting property this buys: under pool-wide slowness nearly every\n * request wants to hedge while successes (the refills) stagnate, so the bucket\n * drains and hedging auto-disables instead of doubling load into public-node\n * rate limits — the standard hedged-request guard (cf. gRPC's hedging throttle;\n * Dean & Barroso, \"The Tail at Scale\"). One instance per process shared across\n * concurrent calls; plain synchronous mutation is race-free on the JS event\n * loop. Reads config live so runtime tuning via `setResilience` applies.\n * @internal Exported for testing only.\n */\nexport class HedgeBudget {\n private tokens = config.resilience.hedgeBucketCapacity\n\n trySpend(): boolean {\n this.clamp()\n // Epsilon guards fractional-refill float accumulation (10 × 0.1 < 1 in FP64).\n if (this.tokens >= 1 - 1e-9) {\n this.tokens -= 1\n return true\n }\n return false\n }\n\n refill(): void {\n this.clamp()\n this.tokens = Math.min(\n config.resilience.hedgeBucketCapacity,\n this.tokens + config.resilience.hedgeRefillPerSuccess\n )\n }\n\n /** Capacity may be lowered at runtime; never let stored tokens exceed it. */\n private clamp(): void {\n if (this.tokens > config.resilience.hedgeBucketCapacity) {\n this.tokens = config.resilience.hedgeBucketCapacity\n }\n }\n\n /** @internal test hook */\n get available(): number {\n return this.tokens\n }\n\n /** @internal test hook */\n reset(tokens = config.resilience.hedgeBucketCapacity): void {\n this.tokens = tokens\n }\n}\n\n// @internal — exported for the co-located spec only, like the trackers above.\nexport const rpcHedgeBudget = new HedgeBudget()\n\n/**\n * Per-attempt timeout for a read call. A node profiled for THIS profile key\n * (full RPC method / REST api+endpoint template) is given `factor × EWMA` —\n * floored (≥2s) so a moderate spike on a fast call is not cut off, and capped\n * at the caller's ceiling so this can only ever *shorten* the wait. The\n * effect: a node running far above its own baseline for this exact kind of\n * call is abandoned early and failover starts in seconds instead of the full\n * fixed window.\n *\n * Two deliberate exclusions:\n * - `explicit` callers (who passed a timeout argument) keep exactly what they\n * asked for — the documented meaning of the parameter is preserved, and a\n * consumer who knows their call is heavy is never second-guessed.\n * - The profile is per (node, full method) with NO fallback to the node's\n * mixed global EWMA or even the API-prefix average: a baseline dominated by\n * cheap `condenser_api.get_accounts` calls must not set the deadline for a\n * heavy `condenser_api.get_account_history`. An unprofiled (node, method)\n * pair keeps the caller's timeout unchanged (cold start == old behavior).\n */\nfunction adaptiveAttemptTimeout(\n tracker: NodeHealthTracker,\n node: string,\n profileKey: string,\n callerTimeout: number,\n explicit: boolean\n): number {\n const r = config.resilience\n if (!r.adaptiveTimeout || explicit) return callerTimeout\n const ewma = tracker.getUsableLatencyMs(node, profileKey)\n if (ewma === undefined) return callerTimeout\n // EWMAs are fractional, but the result feeds AbortSignal.timeout(), which\n // Node rejects with ERR_OUT_OF_RANGE for non-integer delays (browsers coerce).\n return Math.ceil(\n Math.min(callerTimeout, Math.max(r.adaptiveTimeoutFloorMs, r.adaptiveTimeoutFactor * ewma))\n )\n}\n\n// ── Internal helpers ────────────────────────────────────────────────────────\n\n/** Record a caught error on the health tracker (handles NodeError to avoid double-counting). */\nfunction recordError(tracker: NodeHealthTracker, node: string, e: any, api?: string): void {\n if (e instanceof NodeError) {\n if (e.isRateLimit) {\n // 0 → no usable Retry-After → let recordRateLimit apply escalating backoff.\n tracker.recordRateLimit(node, e.rateLimitMs || undefined)\n } else {\n tracker.recordFailure(node, api)\n }\n } else if (e instanceof RPCError) {\n // RPC-level errors are API-specific (e.g., disabled API)\n tracker.recordFailure(node, api)\n } else {\n // Transport-level failures (DNS, TLS, timeout) affect the whole node\n tracker.recordFailure(node)\n }\n}\n\n/**\n * Passively extract head_block_number from known RPC responses\n * (e.g. `condenser_api.get_dynamic_global_properties`, `database_api.get_dynamic_global_properties`).\n * Silently ignores responses without that shape.\n */\nfunction tryRecordHeadBlock(\n tracker: NodeHealthTracker,\n node: string,\n method: string,\n result: any\n): void {\n if (!result || typeof result !== 'object') return\n if (!method.includes('get_dynamic_global_properties')) return\n const block = (result as any).head_block_number\n if (typeof block === 'number') {\n tracker.recordHeadBlock(node, block)\n }\n}\n\n// ── AbortSignal helpers (browser fallbacks) ─────────────────────────────────\n\n/**\n * Build a TimeoutError \"reason\" for an aborted signal.\n * Prefers the standard `DOMException` when available. Runtimes that ship\n * `AbortController` without `DOMException` (notably React Native / Hermes,\n * old Node < 17) fall back to a plain Error tagged with `name: 'TimeoutError'`\n * — which is what consumers actually check on `signal.reason`.\n */\nfunction createTimeoutReason(): Error {\n if (typeof DOMException !== 'undefined') {\n return new DOMException('The operation was aborted due to timeout', 'TimeoutError')\n }\n const err = new Error('The operation was aborted due to timeout')\n err.name = 'TimeoutError'\n return err\n}\n\n/** AbortSignal.timeout polyfill for pre-Chrome 103 / pre-Safari 16.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to clear the dangling timer. */\nfunction createTimeoutSignal(ms: number): { signal: AbortSignal; cleanup: () => void } {\n // Node's AbortSignal.timeout throws ERR_OUT_OF_RANGE on fractional delays\n // (browsers coerce them), so guard every caller here.\n ms = Math.ceil(ms)\n if (typeof AbortSignal.timeout === 'function') {\n return { signal: AbortSignal.timeout(ms), cleanup: () => {} }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(createTimeoutReason()), ms)\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) }\n}\n\n/** AbortSignal.any polyfill for pre-Chrome 116 / pre-Safari 17.4.\n * Returns { signal, cleanup } — caller must invoke cleanup() on success\n * to remove listeners from the input signals (prevents leaks when the\n * same long-lived signal is reused across many callRPC invocations). */\nfunction mergeSignals(\n primary: AbortSignal,\n secondary?: AbortSignal\n): { signal: AbortSignal; cleanup: () => void } {\n if (!secondary) return { signal: primary, cleanup: () => {} }\n if (typeof AbortSignal.any === 'function') {\n return { signal: AbortSignal.any([primary, secondary]), cleanup: () => {} }\n }\n // Fallback: controller that aborts with the winning signal's reason\n const controller = new AbortController()\n if (primary.aborted) {\n controller.abort(primary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n if (secondary.aborted) {\n controller.abort(secondary.reason)\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n const onPrimaryAbort = () => controller.abort(primary.reason)\n const onSecondaryAbort = () => controller.abort(secondary.reason)\n primary.addEventListener('abort', onPrimaryAbort, { once: true })\n secondary.addEventListener('abort', onSecondaryAbort, { once: true })\n\n const cleanup = () => {\n primary.removeEventListener('abort', onPrimaryAbort)\n secondary.removeEventListener('abort', onSecondaryAbort)\n }\n return { signal: controller.signal, cleanup }\n}\n\n/**\n * Low-level JSON-RPC call to a single node. No failover.\n * Throws RPCError for blockchain rejections, NodeError for HTTP 429/5xx,\n * and generic Error for other transport failures.\n * @param shouldRetry - If true, retries once on the same node for transient errors.\n */\nconst jsonRPCCall = async (\n url: string,\n method: string,\n params: any,\n timeout = config.timeout,\n shouldRetry = false,\n externalSignal?: AbortSignal\n) => {\n const id = Math.floor(Math.random() * 100_000_000)\n const body = {\n jsonrpc: '2.0',\n method,\n params,\n id\n }\n // Merge the per-call timeout with any external abort signal (e.g., SSR\n // request cancellation). Either one firing cancels the fetch.\n // Fallbacks for browsers without AbortSignal.timeout (pre-Chrome 103)\n // or AbortSignal.any (pre-Chrome 116).\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(timeout)\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n const cleanup = () => {\n cleanupTimeout()\n cleanupMerge()\n }\n\n try {\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders() },\n signal\n })\n\n // Handle HTTP-level errors before parsing JSON.\n // Throw NodeError so callers can record health exactly once.\n if (res.status === 429) {\n throw new NodeError(url, `HTTP 429 Rate Limited`, {\n rateLimitMs: parseRetryAfterMs(res.headers.get('Retry-After')),\n isRateLimit: true\n })\n }\n // Any other 5xx is a node-level failure. Common cases:\n // 502 Bad Gateway — upstream HAF/jussi down\n // 503 Service Unavail — node draining / maintenance\n // 504 Gateway Timeout — slow upstream\n // 520-530 — Cloudflare interstitials (1033 tunnel error → 530)\n // Without this branch, the HTML error-page body would fall into res.json()\n // and throw a generic SyntaxError downstream, making failover guess at\n // whether the request reached the node.\n if (res.status >= 500 && res.status < 600) {\n throw new NodeError(url, `HTTP ${res.status} from ${url}`)\n }\n\n const result = (await res.json()) as CallResponse\n if (\n !result ||\n typeof result.id === 'undefined' ||\n result.id !== id ||\n result.jsonrpc !== '2.0'\n ) {\n throw new Error('JSONRPC id mismatch')\n }\n if ('result' in result) {\n return result.result\n }\n if ('error' in result) {\n const e = result.error\n if ('message' in e && 'code' in e) {\n throw new RPCError(e)\n }\n throw result.error\n }\n // No result and no error?\n throw result\n } catch (e) {\n if (e instanceof RPCError) {\n throw e\n }\n // NodeError should not be retried on the same node - it's an HTTP status issue\n if (e instanceof NodeError) {\n throw e\n }\n if (externalSignal?.aborted) {\n throw e\n }\n if (shouldRetry) {\n return jsonRPCCall(url, method, params, timeout, false, externalSignal)\n }\n throw e\n } finally {\n cleanup()\n }\n}\n\n/** Small jitter delay between failover attempts to prevent thundering herd. */\nfunction jitterDelay(): Promise {\n return sleep(50 + Math.random() * 50)\n}\n\n// ── Hedged read attempt ─────────────────────────────────────────────────────\n\n/**\n * One hedged READ attempt: start the primary node, and if it is still pending\n * after `max(hedgeDelayFloorMs, hedgeDelayFactor × primary EWMA)`, race a\n * duplicate against the next healthy untried node. First success wins and the\n * loser is aborted. Resolution rules (mirroring the sequential path exactly):\n *\n * - External abort (caller cancelled): reject immediately, record nothing.\n * - Authoritative RPCError (non-node-level blockchain rejection) from either\n * leg: an answer, not a fault — abort the other leg, reject immediately.\n * - Failover-class failure: record health for that leg (recordError +\n * recordSlowFailure — identical to the sequential catch); if the other leg\n * is still running, keep waiting on it; when both have failed, reject with\n * the last error so the outer loop continues its normal failover.\n * - Primary fails BEFORE the hedge fires: reject immediately (plain failover —\n * hedging only ever races slowness, never a node that failed fast).\n *\n * Health/budget bookkeeping on a win: winner records a normal success sample;\n * if the hedge won, the primary gets a censored latency sample (elapsed at\n * abort — a lower bound on its true latency) so repeated hedge-wins reorder\n * the pool; if the primary won without the hedge ever firing, the budget\n * refills. An aborted hedge leg records nothing (it was never given a fair\n * run). Broadcasts NEVER go through this path (double-broadcast risk) — it is\n * wired into `callRPC` only.\n */\nfunction hedgedRpcAttempt(opts: {\n method: string\n params: any[] | object\n api: string\n primary: string\n /**\n * Pre-selected healthy untried peers (up to a few, in rank order). The\n * actual hedge target is drawn uniformly at random at FIRE time: with many\n * concurrent callers behind one origin IP, always duplicating to the single\n * next-ranked node would concentrate the whole hedge stream on it and could\n * trip its per-IP rate limit — spreading over the top candidates keeps the\n * same budget bound without a single-target hotspot. Marked tried only if\n * the hedge actually fires.\n */\n hedgePool: string[]\n callerTimeout: number\n /** Caller passed an explicit timeout — adaptive shortening is disabled. */\n explicitTimeout: boolean\n /** The call's wall-clock deadline: a hedge must not START past it (it would\n * be a brand-new request the outer loop itself would refuse to start). */\n deadlineAt: number\n externalSignal?: AbortSignal\n /** Lets the outer loop add the hedge node to its tried-set at fire time. */\n onHedgeFired: (node: string) => void\n /** Caller-supplied payload validation — see callRPC's `validate` param. */\n validate?: (result: unknown) => boolean\n}): Promise {\n const {\n method,\n params,\n api,\n primary,\n hedgePool,\n callerTimeout,\n explicitTimeout,\n deadlineAt,\n externalSignal,\n onHedgeFired,\n validate\n } = opts\n return new Promise((resolve, reject) => {\n let done = false\n let pendingLegs = 0\n let hedgeFired = false\n /** The primary settled on its own (success OR failure). A censored latency\n * sample is only valid for a primary that was still in flight when the\n * hedge won — recording one after the primary already failed would\n * fabricate a second sample for a request whose outcome was recorded. */\n let primarySettled = false\n let lastError: any\n let hedgeTimer: ReturnType | undefined\n let primaryStart = 0\n const controllers: AbortController[] = []\n\n /** Settle exactly once: clear the timer, abort every other in-flight leg\n * (their rejections land behind the `done` guard and are dropped). */\n const finish = (settle: () => void) => {\n if (done) return\n done = true\n if (hedgeTimer !== undefined) {\n clearTimeout(hedgeTimer)\n hedgeTimer = undefined\n }\n for (const c of controllers) {\n if (!c.signal.aborted) c.abort()\n }\n settle()\n }\n\n const startLeg = (node: string, isHedge: boolean) => {\n pendingLegs++\n const controller = new AbortController()\n controllers.push(controller)\n // Merge our cancellation handle with the caller's signal; jsonRPCCall\n // merges the result with its own per-attempt timeout signal.\n const merged = mergeSignals(controller.signal, externalSignal)\n const legTimeout = adaptiveAttemptTimeout(\n rpcHealthTracker,\n node,\n method,\n callerTimeout,\n explicitTimeout\n )\n const start = Date.now()\n if (!isHedge) primaryStart = start\n jsonRPCCall(node, method, params, legTimeout, false, merged.signal)\n .then((res) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Same handling as the catch\n // path — record the fault against this node's API health, never\n // record a success for a lie, and let the other leg still win.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(\n `[hive-tx] response validation failed for ${method} from ${node}`\n )\n if (!isHedge && !hedgeFired) {\n finish(() => reject(lastError))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n return\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - start, method)\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n if (isHedge) {\n if (!primarySettled) {\n // Primary lost the race while still in flight: censored sample\n // (lower bound of its true latency) so the ranker learns without\n // marking it as failed. A primary that already failed was fully\n // recorded by its own catch — nothing more to record.\n rpcHealthTracker.recordCensoredLatency(primary, Date.now() - primaryStart, method)\n }\n } else if (!hedgeFired) {\n rpcHedgeBudget.refill()\n }\n finish(() => resolve(res as T))\n })\n .catch((e) => {\n merged.cleanup()\n pendingLegs--\n if (!isHedge) primarySettled = true\n if (done) return // aborted loser (or late settle) — already resolved\n if (externalSignal?.aborted) {\n // Caller cancelled — bail without recording (mirrors sequential path).\n finish(() => reject(e))\n return\n }\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n // Authoritative rejection: an answer, not a node fault.\n finish(() => reject(e))\n return\n }\n // Failover-class failure — record exactly as the sequential catch does.\n recordError(rpcHealthTracker, node, e, api)\n rpcHealthTracker.recordSlowFailure(node, Date.now() - start, method)\n lastError = e\n if (!isHedge && !hedgeFired) {\n // Primary failed fast, before the hedge delay: plain failover.\n finish(() => reject(e))\n return\n }\n if (pendingLegs === 0) {\n finish(() => reject(lastError))\n }\n // else: the other leg is still in flight and may still win.\n })\n }\n\n startLeg(primary, false)\n\n // Delay from the primary's per-method profile (the eligibility gate\n // ensured it is usable); a raced expiry just means the floor applies. It is\n // then clamped BELOW the primary's own attempt window: for a heavy API\n // (EWMA > window/hedgeDelayFactor) the un-clamped delay would land past\n // the primary's timeout-abort — which clears this timer — so hedging would\n // silently never fire for exactly the heavy tail it exists to protect.\n // Firing at ~80% of the window keeps the duplicate meaningful (it starts\n // while the primary is still allowed to win) for every profile shape.\n const ewma = rpcHealthTracker.getUsableLatencyMs(primary, method) ?? 0\n const primaryWindow = adaptiveAttemptTimeout(\n rpcHealthTracker,\n primary,\n method,\n callerTimeout,\n explicitTimeout\n )\n const delay = Math.min(\n Math.max(config.resilience.hedgeDelayFloorMs, config.resilience.hedgeDelayFactor * ewma),\n 0.8 * primaryWindow\n )\n hedgeTimer = setTimeout(() => {\n hedgeTimer = undefined\n if (done || externalSignal?.aborted) return\n // Never START a duplicate past the call's wall-clock deadline — it would\n // extend the hold and spend a token on work the outer loop would refuse.\n if (Date.now() >= deadlineAt) return\n // Candidates were selected before the delay elapsed — re-check health at\n // fire time (one may have been rate-limited meanwhile) BEFORE spending a\n // token, so a stale pool costs nothing. Random draw spreads concurrent\n // callers' duplicates across the top candidates (see hedgePool doc).\n const live = hedgePool.filter((n) => rpcHealthTracker.isNodeHealthy(n, api))\n if (live.length === 0) return\n const target = live[Math.floor(Math.random() * live.length)]\n // Budget check at fire time, not arm time: only actual duplicates spend.\n if (!rpcHedgeBudget.trySpend()) return\n hedgeFired = true\n onHedgeFired(target)\n startLeg(target, true)\n }, delay)\n })\n}\n\n// ── Public API: callRPC ─────────────────────────────────────────────────────\n\n/**\n * Makes API calls to Hive blockchain nodes with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, jitter between retries,\n * and HTTP status awareness (429 rate limiting, 503).\n *\n * If the current node fails, it will automatically try the next healthy node.\n * When all nodes have been tried, wraps around to give earlier nodes another chance\n * until the full retry budget (config.retry) is exhausted.\n * RPCErrors (valid blockchain rejections) are never retried.\n *\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Maximum number of retry attempts (default: config.retry). The\n * wall-clock budget (`config.resilience.totalBudgetFactor` × timeout) may end\n * the failover walk before the retry count is exhausted.\n * @param validate - Optional payload validation. Some nodes return a valid\n * JSON-RPC envelope carrying an impossible payload (e.g. account rows with\n * metadata fields stripped to \"\"), which no transport-level check can catch.\n * When the callback returns false the response is treated as a node fault:\n * recorded against that node's per-API health (repeat offenders get an API\n * cooldown and are deprioritized) and the failover walk continues to the\n * next node instead of returning the lie. Keep validators conservative —\n * reject only payloads the caller KNOWS cannot be correct, or a strict\n * validator turns every node's honest answer into a failover storm.\n * @returns Promise resolving to the API response\n * @throws {RPCError} On blockchain-level errors (bad params, missing authority, etc.)\n * @throws {Error} If all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callRPC } from 'hive-tx'\n *\n * // Get account information\n * const accounts = await callRPC('condenser_api.get_accounts', [['alice']])\n *\n * // Custom timeout and retry settings\n * const data = await callRPC('condenser_api.get_content', ['alice', 'test-post'], 10_000, 5)\n * ```\n */\nexport const callRPC = async (\n method: string,\n params: any[] | object = [],\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal,\n validate?: (result: unknown) => boolean\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n // An explicit timeout argument is authoritative: adaptive shortening only\n // applies to callers who left the window to the SDK (timeout === undefined),\n // so `callRPC(m, p, 10_000)` still means \"give each attempt 10s\" exactly.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const api = apiOf(method)\n // Wall-clock budget across ALL failover attempts. Without it the worst case\n // is (retry+1) × timeout ≈ 30s — exactly the render pile-up this feature\n // exists to prevent — whenever the WHOLE pool is slow (adaptive timeouts\n // rise with the EWMAs and hedging self-throttles, both by design). The\n // deadline is checked before each new attempt AND before a hedge fires; an\n // in-flight attempt still finishes its own window, so the true ceiling is\n // deadline + one attempt window (up to ~2× the window if a hedge fired just\n // before the deadline and the attempt then waits out the hedge leg too).\n // Note this budget also bounds callers who passed an explicit `retry`: the\n // wall clock, not the attempt count, is the stronger promise here.\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Track nodes tried in the current round. When all nodes have been tried,\n // clear the set to allow a second round (wrap-around) using the retry budget.\n const triedInRound = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so nodes with an API-specific cooldown are deprioritized.\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n // Pick the healthiest untried node. If all tried, start a new round.\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n\n // Hedge eligibility for THIS attempt: opted in, the primary has a usable\n // latency profile for this exact method (so the hedge delay is grounded in\n // data — cold starts stay sequential), and healthy untried peers exist.\n let hedgePool: string[] = []\n if (\n config.resilience.hedge &&\n rpcHealthTracker.getUsableLatencyMs(node, method) !== undefined\n ) {\n hedgePool = orderedNodes\n .filter((n) => !triedInRound.has(n) && rpcHealthTracker.isNodeHealthy(n, api))\n .slice(0, 3)\n }\n\n if (hedgePool.length > 0) {\n try {\n // All health/budget recording happens inside the hedged attempt —\n // the catch below must NOT record again (unlike the sequential path).\n return await hedgedRpcAttempt({\n method,\n params,\n api,\n primary: node,\n hedgePool,\n callerTimeout: ceiling,\n explicitTimeout,\n deadlineAt: deadline,\n externalSignal: signal,\n onHedgeFired: (n) => triedInRound.add(n),\n validate\n })\n } catch (e: any) {\n if (e instanceof RPCError && !isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n lastError = e\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n }\n\n const callStart = Date.now()\n try {\n const res = await jsonRPCCall(\n node,\n method,\n params,\n adaptiveAttemptTimeout(rpcHealthTracker, node, method, ceiling, explicitTimeout),\n false,\n signal\n )\n if (validate && !validate(res)) {\n // Well-formed envelope, impossible payload: a node fault the\n // HTTP/JSON-RPC layers cannot see. Count it against this node's API\n // health (never record a success or refill the hedge budget for a\n // lie) and fail over to the next node.\n rpcHealthTracker.recordDefectiveResponse(node, api)\n lastError = new Error(`[hive-tx] response validation failed for ${method} from ${node}`)\n if (attempt < retry) {\n await jitterDelay()\n }\n continue\n }\n rpcHealthTracker.recordSuccess(node, api, Date.now() - callStart, method)\n // An un-hedged success is what earns hedge budget back (see HedgeBudget).\n rpcHedgeBudget.refill()\n tryRecordHeadBlock(rpcHealthTracker, node, method, res)\n return res as T\n } catch (e: any) {\n // RPCErrors: distinguish node-level failures from genuine blockchain rejections.\n // Node-level errors (e.g. -32602 \"Unable to parse endpoint data\" from a sick\n // HAF/jussi backend) should failover; real rejections (bad params, missing\n // authority, etc.) propagate immediately.\n if (e instanceof RPCError) {\n if (!isNodeLevelRPCError(e.code, e.message)) {\n throw e\n }\n // Node-level RPC error — record failure and fall through to failover\n }\n // External abort — stop retrying immediately\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n // A genuinely slow failure (timeout/abort/slow-5xx) is also a latency signal so\n // a node that 200s-but-too-slow or aborts at the timeout is demoted by the\n // ranker, not only by the (transient) failure gate. Measured elapsed, never a\n // constant; recordSlowFailure ignores instant (down-node) failures.\n rpcHealthTracker.recordSlowFailure(node, Date.now() - callStart, method)\n lastError = e\n\n // Add jitter before trying next node\n if (attempt < retry) {\n await jitterDelay()\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callRPC for broadcasts ──────────────────────────────────────\n\n/**\n * Broadcast-safe RPC call. Only retries on pre-connection errors where the\n * request definitively never reached the server (ECONNREFUSED, ENOTFOUND, etc.).\n * On timeouts, HTTP errors, or any ambiguous failure, throws immediately to\n * prevent double-broadcasting transactions.\n *\n * Tries each node once (no wrap-around) since broadcast retries are dangerous.\n *\n * @internal Used by Transaction.broadcast()\n */\nexport const callRPCBroadcast = async (\n method: string,\n params: any[] | object = [],\n timeout = config.broadcastTimeout,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an array')\n }\n if (config.nodes.length === 0) {\n throw new Error('config.nodes is empty')\n }\n const api = apiOf(method)\n // Track which nodes we've already tried - broadcasts must never retry the same node\n const triedNodes = new Set()\n let lastError: any\n\n for (let attempt = 0; attempt < config.nodes.length; attempt++) {\n // Re-evaluate order each attempt so health changes are respected\n const orderedNodes = rpcHealthTracker.getOrderedNodes(config.nodes, api)\n const node = orderedNodes.find((n) => !triedNodes.has(n))\n if (!node) break\n triedNodes.add(node)\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n try {\n const res = await jsonRPCCall(node, method, params, timeout, false, signal)\n // Deliberately no latency sample for broadcasts: broadcast_transaction_synchronous\n // blocks for block inclusion (~1.5–3s+) regardless of the node's read speed, so\n // feeding it into the shared read EWMA would wrongly demote a fast node for reads.\n // The same nodes are profiled by callRPC read traffic, so a genuinely slow node is\n // still demoted there.\n rpcHealthTracker.recordSuccess(node, api)\n return res as T\n } catch (e: any) {\n // RPCErrors are valid blockchain rejections - never retry\n if (e instanceof RPCError) {\n throw e\n }\n if (signal?.aborted) {\n throw e\n }\n recordError(rpcHealthTracker, node, e, api)\n lastError = e\n\n // Broadcast safety: only fail over when the request is safe to re-send.\n // `broadcastOperations` signs the tx exactly once and `callRPCBroadcast`\n // reuses that signed payload across nodes, so any case where the next\n // node would dedupe by trx_id is fine. RPCErrors (real blockchain\n // rejections) propagate immediately — see isBroadcastSafeToRetry.\n if (!isBroadcastSafeToRetry(e)) {\n throw e\n }\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callREST ────────────────────────────────────────────────────\n\nconst apiMethods: Record = {\n balance: '/balance-api',\n hafah: '/hafah-api',\n hafbe: '/hafbe-api',\n hivemind: '/hivemind-api',\n hivesense: '/hivesense-api',\n reputation: '/reputation-api',\n 'nft-tracker': '/nft-tracker-api',\n hafsql: '/hafsql',\n status: '/status-api'\n}\n\n/**\n * Makes REST API calls to Hive blockchain REST endpoints with automatic retry and failover support.\n * Uses per-request retry counters, node health tracking, and timeout support.\n * Wraps around the node list to honor the full retry budget.\n *\n * @template Api - The REST API method type (e.g., 'balance', 'hafah', 'hivemind', etc.)\n * @template P - The endpoint path type for the specified API\n *\n * @param api - The REST API method name to call\n * @param endpoint - The specific endpoint path within the API\n * @param params - Optional parameters for path and query string replacement\n * @param timeout - Request timeout in milliseconds (default: config.timeout)\n * @param retry - Number of retry attempts before throwing an error (default:\n * config.retry). The wall-clock budget (`config.resilience.totalBudgetFactor`\n * × timeout) may end the failover walk before the retry count is exhausted.\n *\n * @returns Promise resolving to the API response data with proper typing\n * @throws Error if all retry attempts fail\n *\n * @example\n * ```typescript\n * import { callREST } from 'hive-tx'\n *\n * // Get account balance\n * const balance = await callREST('balance', '/accounts/{account-name}/balances', { \"account-name\": 'alice' })\n *\n * // Custom timeout and retry settings\n * const data = await callREST('status', '/status', undefined, 10_000, 3)\n * ```\n */\nexport async function callREST(\n api: APIMethods,\n endpoint: string,\n params?: Record,\n timeout?: number,\n retry = config.retry,\n signal?: AbortSignal\n): Promise {\n if (!Array.isArray(config.restNodes)) {\n throw new Error('config.restNodes is not an array')\n }\n if (config.restNodes.length === 0) {\n throw new Error('config.restNodes is empty')\n }\n // Same contract as callRPC: an explicit timeout argument is authoritative\n // (no adaptive shortening), and a wall-clock deadline bounds the total\n // failover walk when the whole pool is slow.\n const explicitTimeout = timeout !== undefined\n const ceiling = timeout ?? config.timeout\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n // Latency-profile key: api + endpoint TEMPLATE (pre-substitution, so the\n // cardinality is code-defined) — a cheap endpoint's baseline must not set\n // the deadline for a heavy one within the same REST api.\n const restProfileKey = `${api}:${endpoint}`\n // Per-API node override: an API served by only a subset of nodes (e.g.\n // hivesense) uses its own capable-host list so the small retry budget and\n // cold starts aren't wasted on nodes that 404/503 it. Any API without an\n // override (or with an empty one) falls back to the generic restNodes.\n const apiNodes =\n config.restNodesByApi?.[api]?.length\n ? config.restNodesByApi[api]!\n : config.restNodes\n const triedInRound = new Set()\n let lastError: any\n // Track whether the error was already recorded by the HTTP status handler\n let alreadyRecorded = false\n\n for (let attempt = 0; attempt <= retry; attempt++) {\n if (attempt > 0 && Date.now() >= deadline) {\n break\n }\n // Re-evaluate node order each attempt so health changes are respected.\n // Pass api so per-API cooldowns are respected.\n const orderedNodes = restHealthTracker.getOrderedNodes(apiNodes, api)\n let node = orderedNodes.find((n) => !triedInRound.has(n))\n if (!node) {\n triedInRound.clear()\n node = orderedNodes[0]\n }\n triedInRound.add(node)\n const baseUrl = node + apiMethods[api]\n let path = endpoint as string\n const paramObj = params || ({} as Record)\n const processedPathParams = new Set()\n\n // Replace path params ONLY\n Object.entries(paramObj).forEach(([key, value]) => {\n if (path.includes(`{${key}}`)) {\n path = path.replace(`{${key}}`, encodeURIComponent(String(value)))\n processedPathParams.add(key)\n }\n })\n const url = new URL(baseUrl + path)\n // Add ONLY remaining params as query (if any)\n Object.entries(paramObj).forEach(([key, value]) => {\n if (!processedPathParams.has(key)) {\n if (Array.isArray(value)) {\n value.forEach((v) => url.searchParams.append(key, String(v)))\n } else {\n url.searchParams.set(key, String(value))\n }\n }\n })\n\n if (signal?.aborted) {\n throw new Error('Aborted')\n }\n alreadyRecorded = false\n // Adaptive per-attempt timeout (see adaptiveAttemptTimeout): a profiled\n // REST node is abandoned at factor×EWMA instead of the full fixed window.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n adaptiveAttemptTimeout(restHealthTracker, node, restProfileKey, ceiling, explicitTimeout)\n )\n const { signal: restSignal, cleanup: cleanupMerge } = mergeSignals(tSignal, signal)\n const restCleanup = () => { cleanupTimeout(); cleanupMerge() }\n const restCallStart = Date.now()\n try {\n const response = await fetch(url.toString(), {\n signal: restSignal,\n headers: serverIdentityHeaders()\n })\n if (response.status === 404) {\n throw new Error('HTTP 404 - Hint: can happen on wrong params')\n }\n if (response.status === 429) {\n // 0 (no usable Retry-After) → undefined → escalating backoff in recordRateLimit.\n restHealthTracker.recordRateLimit(\n node,\n parseRetryAfterMs(response.headers.get('Retry-After')) || undefined\n )\n alreadyRecorded = true\n throw new Error(`HTTP 429 Rate Limited by ${node}`)\n }\n if (response.status === 503) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP 503 Service Unavailable from ${node}`)\n }\n if (!response.ok) {\n restHealthTracker.recordFailure(node, api)\n alreadyRecorded = true\n throw new Error(`HTTP ${response.status} from ${node}`)\n }\n restHealthTracker.recordSuccess(node, api, Date.now() - restCallStart, restProfileKey)\n return response.json() as any\n } catch (e: any) {\n // 404 is not a node issue, don't failover\n if (e?.message?.includes('HTTP 404')) {\n throw e\n }\n // External abort (caller unmounted / React Query cancelled the request) is the\n // client's decision, NOT a node fault. Mirror callRPC: bail before recording any\n // failure or slow-latency sample so a healthy REST node (e.g. an own node) is never\n // demoted by routine navigation/cancellation.\n if (signal?.aborted) {\n throw e\n }\n // Only record if not already recorded by 429/503 handler above\n if (!alreadyRecorded) {\n restHealthTracker.recordFailure(node, api)\n }\n // A slow failure (timeout/abort/slow-5xx — e.g. an own node from a far region) is a\n // latency signal too, so it is demoted by the ranker, not only the failure gate.\n // Measured elapsed; recordSlowFailure floors at LATENCY_SLOW_FAILURE_MS so a fast\n // 404/429 or instant down-node failure is NOT mis-read as \"slow\".\n restHealthTracker.recordSlowFailure(node, Date.now() - restCallStart, restProfileKey)\n lastError = e\n\n if (attempt < retry) {\n await jitterDelay()\n }\n } finally {\n restCleanup()\n }\n }\n\n throw lastError\n}\n\n// ── Public API: callWithQuorum ───────────────────────────────────────────────\n\n/**\n * Make a JSONRPC call with quorum. The method will cross-check the result\n * with `quorum` number of nodes before returning the result.\n * @param method - The API method name (e.g., 'condenser_api.get_accounts')\n * @param params - Parameters for the API method as array or object\n * @param quorum - Default: 2 (recommended)\n */\nexport const callWithQuorum = async (\n method: string,\n params: any[] | object = [],\n quorum = 2,\n signal?: AbortSignal\n): Promise => {\n if (!Array.isArray(config.nodes)) {\n throw new Error('config.nodes is not an Array')\n }\n if (quorum > config.nodes.length) {\n throw new Error('quorum > config.nodes.length')\n }\n // We call random nodes for better security (Fisher-Yates shuffle)\n const shuffleNodes = (arr: string[]) => {\n const a = [...arr]\n for (let i = a.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [a[i], a[j]] = [a[j], a[i]]\n }\n return a\n }\n let allNodes = shuffleNodes(config.nodes)\n let currentBatchSize = Math.min(quorum, allNodes.length)\n let allResults: any[] = []\n while (currentBatchSize > 0 && allNodes.length > 0) {\n // Take next batch of nodes\n const batchNodes = allNodes.splice(0, currentBatchSize)\n const promises: Promise[] = []\n const batchResults: any[] = []\n // Launch batch calls in parallel\n for (let i = 0; i < batchNodes.length; i++) {\n promises.push(\n jsonRPCCall(batchNodes[i], method, params, undefined, true, signal)\n .then((data) => batchResults.push(data))\n .catch(() => {})\n )\n }\n await Promise.all(promises)\n allResults.push(...batchResults)\n // Check for consensus in successful results\n const consensusResult = findConsensus(allResults, quorum)\n if (consensusResult) {\n return consensusResult\n }\n // Prepare next batch\n currentBatchSize = Math.min(quorum, allNodes.length)\n if (currentBatchSize === 0) {\n throw new Error('No more nodes available.')\n }\n }\n throw new Error(\"Couldn't reach quorum.\")\n}\n\nfunction findConsensus(results: any[], quorum: number) {\n const resultGroups = new Map()\n for (const result of results) {\n const key = JSON.stringify(result)\n if (!resultGroups.has(key)) {\n resultGroups.set(key, [])\n }\n resultGroups.get(key)!.push(result)\n }\n const consensusGroup = Array.from(resultGroups.values()).find((group) => group.length >= quorum)\n return consensusGroup ? consensusGroup[0] : null\n}\n","import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\nimport { PrivateKey } from './helpers/PrivateKey'\nimport {\n OperationName,\n OperationBody,\n TransactionType,\n TransactionStatus,\n BroadcastResult\n} from './types'\nimport { ByteBuffer } from './helpers/ByteBuffer'\nimport { Serializer } from './helpers/serializer'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { config } from './config'\nimport { callRPC, callRPCBroadcast, RPCError } from './helpers/call'\nimport { DigestData } from './types'\nimport { sleep } from './helpers/sleep'\n\nconst chainId = hexToBytes(config.chain_id)\n\ninterface TransactionOptions {\n transaction?: TransactionType | Transaction\n /**\n * Transaction expiration in milliseconds (ms) - max 86400000 (24 hours)\n * @default 60_000\n */\n expiration?: number\n}\n\nexport class Transaction {\n transaction?: TransactionType\n\n expiration: number = 60_000\n\n private txId?: string\n\n constructor(options?: TransactionOptions) {\n if (options?.transaction) {\n if (options.transaction instanceof Transaction) {\n this.transaction = options.transaction.transaction\n this.expiration = options.transaction.expiration\n } else {\n this.transaction = options.transaction\n }\n // A transaction built externally (e.g. from a hive-uri signing request)\n // may omit the `signatures` array. sign(), addSignature() and broadcast()\n // all assume it exists, so normalize it here to avoid\n // \"Cannot read property 'push' of undefined\" on sign.\n if (this.transaction && !Array.isArray(this.transaction.signatures)) {\n this.transaction.signatures = []\n }\n this.txId = this.digest().txId\n }\n if (options?.expiration) {\n this.expiration = options.expiration\n }\n }\n\n /**\n * Adds an operation to the transaction. If no transaction exists, creates one first.\n * @template O Operation name type for type safety\n * @param operationName The name/type of the operation to add (e.g., 'transfer', 'vote', 'comment')\n * @param operationBody The operation data/body for the specified operation type\n * @returns Promise that resolves when the operation is added\n * @throws Error if transaction creation fails or global properties cannot be retrieved\n */\n async addOperation(\n operationName: O,\n operationBody: OperationBody\n ): Promise {\n if (!this.transaction) {\n await this.createTransaction(this.expiration)\n }\n this.transaction!.operations.push([operationName, operationBody])\n }\n\n /**\n * Signs the transaction with the provided key(s), supporting both single and multi-signature transactions.\n * For multi-signature, you can sign with all keys at once or sign individually by calling this method multiple times.\n * @param keys Single PrivateKey or array of PrivateKeys to sign the transaction with\n * @returns The signed transaction\n * @throws Error if no transaction exists to sign\n */\n sign(keys: PrivateKey | PrivateKey[]): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n if (this.transaction) {\n const { digest, txId } = this.digest()\n if (!Array.isArray(keys)) {\n keys = [keys]\n }\n for (const key of keys) {\n const signature = key.sign(digest)\n this.transaction.signatures.push(signature.customToString())\n }\n this.txId = txId\n return this.transaction\n } else {\n throw new Error('No transaction to sign')\n }\n }\n\n /**\n * Broadcasts the signed transaction to the Hive network.\n * Automatically handles retries and duplicate transaction detection.\n * @param checkStatus By default (false) the transaction is not guaranteed to be included in a block.\n * For example the transaction can expire while waiting in mempool.\n * If you pass true here, the function will wait for the transaction to be either included or dropped\n * before returning a result.\n * @returns Promise resolving to broadcast result\n * @throws Error if no transaction exists or transaction is not signed or transaction got rejected\n */\n async broadcast(checkStatus = false): Promise {\n if (!this.transaction) {\n throw new Error(\n 'Attempted to broadcast an empty transaction. Add operations by .addOperation()'\n )\n }\n if (this.transaction.signatures.length === 0) {\n throw new Error(\n 'Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)'\n )\n }\n try {\n await callRPCBroadcast('condenser_api.broadcast_transaction', [this.transaction])\n } catch (e) {\n if (e instanceof RPCError && e.message.includes('Duplicate transaction check failed')) {\n // ignore duplicate transaction error as this can happen when we retry the broadcast\n } else {\n throw e\n }\n }\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n if (!checkStatus) {\n return { tx_id: this.txId, status: 'unknown' }\n }\n // Poll until the transaction reaches a final state or max attempts exceeded.\n // With 60 attempts: delays grow from 1.3s to 19s, total wait ~10 minutes.\n const maxPollAttempts = 60\n await sleep(1000)\n let status = await this.checkStatus()\n let i = 1\n while (\n status?.status !== 'within_irreversible_block' &&\n status?.status !== 'expired_irreversible' &&\n status?.status !== 'too_old' &&\n i < maxPollAttempts\n ) {\n await sleep(1000 + i * 300)\n status = await this.checkStatus()\n i++\n }\n return {\n tx_id: this.txId,\n status: (status?.status ?? 'unknown') as BroadcastResult['status']\n }\n }\n\n /**\n * Returns the transaction digest containing the transaction ID and hash.\n * The digest can be used to verify signatures and for transaction identification.\n * @returns DigestData containing transaction ID and hash\n * @throws Error if no transaction exists\n */\n digest(): DigestData {\n if (!this.transaction) {\n throw new Error('First create a transaction by .addOperation()')\n }\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n const temp = { ...this.transaction }\n try {\n Serializer.Transaction(buffer, temp)\n } catch (cause) {\n throw new Error('Unable to serialize transaction: ' + cause)\n }\n buffer.flip()\n const transactionData = new Uint8Array(buffer.toBuffer())\n const txId = bytesToHex(sha256(transactionData)).slice(0, 40)\n const digest = sha256(new Uint8Array([...chainId, ...transactionData]))\n return { digest, txId }\n }\n\n /**\n * Adds a signature to an already created transaction. Useful when signing with external tools.\n * Multiple signatures can be added one at a time for multi-signature transactions.\n * @param signature The signature string in hex format (must be exactly 130 characters)\n * @returns The transaction with the added signature\n * @throws Error if no transaction exists or signature format is invalid\n */\n addSignature(signature: string): TransactionType {\n if (!this.transaction) {\n throw new Error('First create a transaction by .create(operations)')\n }\n if (typeof signature !== 'string') {\n throw new Error('Signature must be string')\n }\n if (signature.length !== 130) {\n throw new Error('Signature must be 130 characters long')\n }\n this.transaction.signatures.push(signature)\n return this.transaction\n }\n\n /** Get status of this transaction. Usually called internally after broadcasting. */\n async checkStatus(): Promise {\n if (!this.txId) {\n this.txId = this.digest().txId\n }\n return callRPC('transaction_status_api.find_transaction', {\n transaction_id: this.txId,\n expiration: this.transaction?.expiration\n })\n }\n\n /**\n * Creates the transaction structure and initializes it with blockchain data.\n * Retrieves current head block information and sets up reference block data.\n * @private\n * @param expiration Transaction expiration in milliseconds\n */\n private createTransaction = async (expiration: number) => {\n const props = await callRPC('condenser_api.get_dynamic_global_properties', [])\n const bytes = hexToBytes(props.head_block_id)\n const refBlockPrefix = Number(new Uint32Array(bytes.buffer, bytes.byteOffset + 4, 1)[0])\n const expirationIso = new Date(Date.now() + expiration).toISOString().slice(0, -5)\n this.transaction = {\n expiration: expirationIso,\n extensions: [],\n operations: [],\n ref_block_num: props.head_block_number & 0xffff,\n ref_block_prefix: refBlockPrefix,\n signatures: []\n }\n }\n}\n","import bs58 from 'bs58'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PublicKey } from './PublicKey'\nimport { Signature } from './Signature'\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport type KeyRole = 'owner' | 'active' | 'posting' | 'memo'\n\nconst NETWORK_ID = new Uint8Array([0x80])\n\n/**\n * ECDSA (secp256k1) private key for signing and encryption operations.\n * Handles key generation, derivation from seeds/passwords, and cryptographic operations.\n *\n * All private keys are stored internally as Uint8Array and can be converted to/from\n * Wallet Import Format (WIF) strings for storage and transmission.\n *\n * @example\n * ```typescript\n * // From WIF string\n * const key = PrivateKey.from('5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw')\n *\n * // Generate random key\n * const randomKey = PrivateKey.randomKey()\n *\n * // From username and password\n * const loginKey = PrivateKey.fromLogin('username', 'password')\n *\n * // Sign a message\n * const signature = key.sign(someHash)\n *\n * // Get public key\n * const pubKey = key.createPublic()\n * ```\n */\nexport class PrivateKey {\n key: Uint8Array\n\n constructor(key: Uint8Array) {\n this.key = key\n try {\n secp256k1.getPublicKey(key)\n } catch (e) {\n throw new Error('invalid private key')\n }\n }\n\n /**\n * Creates a PrivateKey instance from a WIF string or raw Uint8Array.\n * Automatically detects the input type and uses the appropriate method.\n *\n * @param value - WIF formatted string or raw 32-byte key as Uint8Array\n * @returns New PrivateKey instance\n * @throws Error if the key format is invalid\n */\n static from(value: string | Uint8Array): PrivateKey {\n if (typeof value === 'string') {\n return PrivateKey.fromString(value)\n } else {\n return new PrivateKey(value)\n }\n }\n\n /**\n * Creates a PrivateKey from a Wallet Import Format (WIF) encoded string.\n *\n * @param wif - WIF encoded private key string\n * @returns New PrivateKey instance\n * @throws Error if WIF format is invalid or checksum fails\n */\n static fromString(wif: string): PrivateKey {\n return new PrivateKey(decodePrivate(wif).subarray(1))\n }\n\n /**\n * Creates a PrivateKey from a seed string or Uint8Array.\n * The seed is hashed with SHA256 to produce the private key.\n *\n * @param seed - Seed string (converted to bytes) or raw byte array\n * @returns New PrivateKey instance derived from seed\n */\n static fromSeed(seed: string | Uint8Array): PrivateKey {\n if (typeof seed === 'string') {\n const isHex = /^[0-9a-fA-F]+$/.test(seed)\n if (isHex) {\n seed = hexToBytes(seed)\n } else {\n // Convert non-hex string to Uint8Array using UTF-8 encoding\n // Avoid top-level TextEncoder — not available on all runtimes (e.g. Hermes)\n const bytes: number[] = []\n for (let i = 0; i < seed.length; i++) {\n let c = seed.charCodeAt(i)\n if (c < 0x80) {\n bytes.push(c)\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < seed.length) {\n const next = seed.charCodeAt(++i)\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff)\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))\n }\n }\n seed = new Uint8Array(bytes)\n }\n }\n return new PrivateKey(sha256(seed))\n }\n\n /**\n * Derives a PrivateKey from username, password, and role using Hive's key derivation scheme.\n * This generates the same keys that the Hive wallet uses for login-based keys.\n *\n * @param username - Hive username\n * @param password - Master password (or seed phrase)\n * @param role - Key role ('owner', 'active', 'posting', 'memo')\n * @returns New PrivateKey instance for the specified role\n */\n static fromLogin(username: string, password: string, role: KeyRole = 'active'): PrivateKey {\n const seed = username + role + password\n return PrivateKey.fromSeed(seed)\n }\n\n /**\n * Signs a 32-byte message hash using ECDSA and returns a recoverable signature.\n * The signature includes recovery information to allow public key recovery.\n *\n * @param message - 32-byte message hash to sign (Uint8Array)\n * @returns Signature object containing the signature data\n */\n sign(message: Uint8Array): Signature {\n const rv = secp256k1.sign(message, this.key, {\n extraEntropy: true,\n format: 'recovered',\n prehash: false // prehash does sha256 on the message\n })\n const recovery = parseInt(bytesToHex(rv.subarray(0, 1)), 16)\n return Signature.from((recovery + 31).toString(16) + bytesToHex(rv.subarray(1)))\n }\n\n /**\n * Derives the corresponding public key for this private key.\n *\n * @param prefix - Optional address prefix (defaults to config.address_prefix)\n * @returns PublicKey instance derived from this private key\n */\n createPublic(prefix?: string): PublicKey {\n return new PublicKey(secp256k1.getPublicKey(this.key), prefix)\n }\n\n /**\n * Returns the private key as a Wallet Import Format (WIF) encoded string.\n * This includes network ID and checksum for safe storage/transmission.\n *\n * @returns WIF encoded private key string\n */\n toString(): string {\n return encodePrivate(new Uint8Array([...NETWORK_ID, ...this.key]))\n }\n\n /**\n * Returns a masked representation of the private key for debugging/logging.\n * Shows only the first and last 6 characters to avoid accidental exposure.\n * Use toString() to get the full key for export/serialization.\n *\n * @returns Masked key representation for safe logging\n */\n inspect(): string {\n const key = this.toString()\n return `PrivateKey: ${key.slice(0, 6)}...${key.slice(-6)}`\n }\n\n /**\n * Computes a shared secret using ECDH key exchange for memo encryption.\n * The shared secret is used as a key for AES encryption/decryption.\n *\n * @param publicKey - Other party's public key\n * @returns 64-byte shared secret as Uint8Array\n */\n getSharedSecret(publicKey: PublicKey): Uint8Array {\n const s = secp256k1.getSharedSecret(this.key, publicKey.key)\n // strip the parity byte\n return sha512(s.subarray(1))\n }\n\n /**\n * Generates a new cryptographically secure random private key.\n * Uses the secp256k1 key generation algorithm for security.\n * This method may take up to 250ms due to entropy collection.\n *\n * @returns New randomly generated PrivateKey instance\n */\n static randomKey(): PrivateKey {\n return new PrivateKey(secp256k1.keygen().secretKey)\n }\n}\n\nconst doubleSha256 = (input: Uint8Array) => {\n const dbl = sha256(sha256(input))\n return dbl\n}\n\n/** Encode bs58+doubleSha256-checksum private key. */\nconst encodePrivate = (key: Uint8Array) => {\n // assert.equal(key.readUInt8(0), 0x80, 'private key network id mismatch')\n const checksum = doubleSha256(key)\n return bs58.encode(new Uint8Array([...key, ...checksum.slice(0, 4)]))\n}\n\n/** Decode bs58+doubleSha256-checksum encoded private key. */\nconst decodePrivate = (encodedKey: string) => {\n const buffer = bs58.decode(encodedKey)\n if (!isUint8ArrayEqual(buffer.slice(0, 1), NETWORK_ID)) {\n throw new Error('Private key network id mismatch')\n }\n const checksum = buffer.slice(-4)\n const key = buffer.slice(0, -4)\n const checksumVerify = doubleSha256(key).slice(0, 4)\n if (!isUint8ArrayEqual(checksum, checksumVerify)) {\n throw new Error('Private key checksum mismatch')\n }\n return key\n}\n\nconst isUint8ArrayEqual = (a: Uint8Array, b: Uint8Array) => {\n if (a === b) return true\n if (a.byteLength !== b.byteLength) return false\n const len = a.byteLength\n let i = 0\n while (i < len && a[i] === b[i]) i++\n return i === len\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { cbc as AESCBC } from '@noble/ciphers/aes.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { sha256, sha512 } from '@noble/hashes/sha2.js'\nimport { PrivateKey } from './PrivateKey'\nimport { PublicKey } from './PublicKey'\n\nexport const encrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n message: Uint8Array,\n nonce: bigint = uniqueNonce()\n) => crypt(privateKey, publicKey, nonce, message)\n\nexport const decrypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum: number\n): Uint8Array => {\n const d = crypt(privateKey, publicKey, nonce, message, checksum)\n return d.message\n}\n\n/**\n * @arg message - Encrypted or plain text message (see checksum)\n * @arg checksum - shared secret checksum (null to encrypt, non-null to decrypt)\n */\nconst crypt = (\n privateKey: PrivateKey,\n publicKey: PublicKey,\n nonce: bigint,\n message: Uint8Array,\n checksum?: number\n): { nonce: bigint; message: Uint8Array; checksum: number } => {\n const nonceL = nonce\n const S = privateKey.getSharedSecret(publicKey)\n let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n ebuf.writeUint64(nonceL)\n ebuf.append(S)\n ebuf.flip()\n\n const encryptionKey = sha512(new Uint8Array(ebuf.toBuffer()))\n const iv = encryptionKey.subarray(32, 48)\n const tag = encryptionKey.subarray(0, 32)\n\n // check if first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.\n const check = sha256(encryptionKey).subarray(0, 4)\n const cbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n cbuf.append(check)\n cbuf.flip()\n const check32 = cbuf.readUint32()\n if (checksum !== undefined) {\n if (check32 !== checksum) {\n throw new Error('Invalid key')\n }\n message = cryptoJsDecrypt(message, tag, iv)\n } else {\n message = cryptoJsEncrypt(message, tag, iv)\n }\n return { nonce: nonceL, message, checksum: check32 }\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} ciphertext - binary format\n * @return {Uint8Array} the decrypted message\n */\nconst cryptoJsDecrypt = (message: Uint8Array, tag: Uint8Array, iv: Uint8Array): Uint8Array => {\n let messageBuffer = message\n const decipher = AESCBC(tag, iv)\n messageBuffer = decipher.decrypt(messageBuffer)\n return messageBuffer\n}\n\n/**\n * This method does not use a checksum, the returned data must be validated some other way.\n * @arg {string|Uint8Array} plaintext - binary format\n * @return {Uint8Array} binary\n */\nexport const cryptoJsEncrypt = (\n message: Uint8Array,\n tag: Uint8Array,\n iv: Uint8Array\n): Uint8Array => {\n let messageBuffer = message\n const cipher = AESCBC(tag, iv)\n messageBuffer = cipher.encrypt(messageBuffer)\n return messageBuffer\n}\n\nlet uniqueNonceEntropy: number | null = null\n\nconst uniqueNonce = (): bigint => {\n if (uniqueNonceEntropy === null) {\n const randomPrivateKey = secp256k1.utils.randomSecretKey()\n uniqueNonceEntropy = (randomPrivateKey[0] << 8) | randomPrivateKey[1]\n }\n let long = BigInt(Date.now())\n const entropy = ++uniqueNonceEntropy % 0x10000\n long = (long << BigInt(16)) | BigInt(entropy)\n return long\n}\n","import { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\n\nconst PublicKeyDeserializer = (buf: ByteBuffer) => {\n const c = fixedBuf(buf, 33)\n return new PublicKey(c)\n}\n\nconst UInt64Deserializer = (b: ByteBuffer) => {\n return b.readUint64()\n}\n\nconst UInt32Deserializer = (b: ByteBuffer) => {\n return b.readUint32()\n}\n\nconst BinaryDeserializer = (b: ByteBuffer) => {\n const len = b.readVarint32()\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n}\n\nconst BufferDeserializer = (keyDeserializers: any) => (buf: Uint8Array) => {\n const obj: any = {}\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n buffer.append(buf)\n buffer.flip()\n for (const [key, deserializer] of keyDeserializers) {\n try {\n obj[key] = deserializer(buffer)\n } catch (error: any) {\n error.message = `${key}: ${error.message}`\n throw error\n }\n }\n return obj\n}\n\nfunction fixedBuf(b: ByteBuffer, len: number) {\n if (!b) {\n throw Error('No buffer found on first parameter')\n } else {\n const bCopy = b.copy(b.offset, b.offset + len)\n b.skip(len)\n return new Uint8Array(bCopy.toBuffer())\n }\n}\n\nconst EncryptedMemoDeserializer = BufferDeserializer([\n ['from', PublicKeyDeserializer],\n ['to', PublicKeyDeserializer],\n ['nonce', UInt64Deserializer],\n ['check', UInt32Deserializer],\n ['encrypted', BinaryDeserializer]\n])\n\nexport const Deserializer = {\n Memo: EncryptedMemoDeserializer\n}\n","import bs58 from 'bs58'\nimport { ByteBuffer } from './ByteBuffer'\nimport { Serializer } from './serializer'\nimport { PrivateKey } from './PrivateKey'\nimport * as Aes from './aes'\nimport { PublicKey } from './PublicKey'\nimport { Deserializer } from './deserializer'\n\nexport type Memo = {\n /**\n * Encrypts a memo for secure private messaging\n */\n encode(\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n ): string\n\n /**\n * Decrypts a memo message\n */\n decode(privateKey: string | PrivateKey, memo: string): string\n}\n\n/**\n * Encodes a memo using AES encryption for secure private messaging on Hive.\n * Messages must start with '#' to be encrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Sender's private memo key (string WIF format or PrivateKey instance)\n * @param publicKey - Recipient's public memo key (string or PublicKey instance)\n * @param memo - Message to encrypt (must start with '#' for encryption)\n * @param testNonce - Optional nonce for testing (advanced usage)\n * @returns Encrypted memo string prefixed with '#'\n * @throws Error if encryption is not supported in current environment\n */\nconst encode = (\n privateKey: string | PrivateKey,\n publicKey: string | PublicKey,\n memo: string,\n testNonce?: any\n): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n publicKey = toPublicObj(publicKey)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.writeVString(memo)\n const memoBuffer = new Uint8Array(mbuf.copy(0, mbuf.offset).toBuffer())\n const { nonce, message, checksum } = Aes.encrypt(privateKey, publicKey, memoBuffer, testNonce)\n const mbuf2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n Serializer.Memo(mbuf2, {\n check: checksum,\n encrypted: message,\n from: privateKey.createPublic(),\n nonce,\n to: publicKey\n })\n mbuf2.flip()\n const data = new Uint8Array(mbuf2.toBuffer())\n return '#' + bs58.encode(data)\n}\n\n/**\n * Decrypts an encrypted memo using AES decryption.\n * Messages must start with '#' to be decrypted. Plain text messages are returned unchanged.\n *\n * @param privateKey - Recipient's private memo key (string WIF format or PrivateKey instance)\n * @param memo - Encrypted memo string (must start with '#' for decryption)\n * @returns Decrypted memo content with '#' prefix\n * @throws Error if decryption fails or encryption not supported in current environment\n */\nconst decode = (privateKey: string | PrivateKey, memo: string): string => {\n if (!memo.startsWith('#')) {\n return memo\n }\n memo = memo.substring(1)\n checkEncryption()\n privateKey = toPrivateObj(privateKey)\n // memo = bs58.decode(memo)\n let memoBuffer = Deserializer.Memo(bs58.decode(memo))\n const { from, to, nonce, check, encrypted } = memoBuffer\n const pubkey = privateKey.createPublic().toString()\n const otherpub =\n pubkey === new PublicKey(from.key).toString() ? new PublicKey(to.key) : new PublicKey(from.key)\n memoBuffer = Aes.decrypt(privateKey, otherpub, nonce, encrypted, check)\n const mbuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n mbuf.append(memoBuffer)\n mbuf.flip()\n return '#' + mbuf.readVString()\n}\n\nlet encodeTest: boolean | undefined\nconst checkEncryption = () => {\n if (encodeTest === undefined) {\n let plaintext\n encodeTest = true // prevent infinate looping\n try {\n const wif = '5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw'\n const pubkey = 'STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA'\n const cyphertext = encode(wif, pubkey, '#memo爱')\n plaintext = decode(wif, cyphertext)\n } finally {\n encodeTest = plaintext === '#memo爱'\n }\n }\n if (encodeTest === false) {\n throw new Error('This environment does not support encryption.')\n }\n}\n\nconst toPrivateObj = (o: string | PrivateKey): PrivateKey => {\n if (typeof o === 'string') {\n return PrivateKey.fromString(o)\n } else {\n return o\n }\n}\nconst toPublicObj = (o: string | PublicKey): PublicKey => {\n if (typeof o === 'string') {\n return PublicKey.fromString(o)\n } else {\n return o\n }\n}\n\n/**\n * Memo utilities for encrypting and decrypting private messages between Hive users.\n * Uses AES encryption with ECDH key exchange for secure communication.\n *\n * Messages must start with '#' to be encrypted/decrypted.\n * Plain text messages (without '#') are returned unchanged.\n *\n * @example\n * ```typescript\n * import { Memo, PrivateKey, PublicKey } from 'hive-tx'\n *\n * // Encrypt a message\n * const encrypted = Memo.encode(senderPrivateKey, recipientPublicKey, '#Hello World')\n *\n * // Decrypt a message\n * const decrypted = Memo.decode(recipientPrivateKey, encrypted)\n * console.log(decrypted) // '#Hello World'\n * ```\n */\nexport const Memo = {\n decode,\n encode\n}\n","import { Serializer } from './serializer'\nimport { ByteBuffer } from './ByteBuffer'\nimport { PublicKey } from './PublicKey'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nexport interface WitnessProps {\n account_creation_fee?: string\n account_subsidy_budget?: number\n account_subsidy_decay?: number\n key: PublicKey | string\n maximum_block_size?: number\n new_signing_key?: PublicKey | string | null\n hbd_exchange_rate?: { base: string; quote: string }\n hbd_interest_rate?: number\n url?: string\n}\n\n/** Return null for a valid username */\nexport const validateUsername = (username: string): null | string => {\n let suffix = 'Account name should '\n if (!username) {\n return suffix + 'not be empty.'\n }\n const length = username.length\n if (length < 3) {\n return suffix + 'be longer.'\n }\n if (length > 16) {\n return suffix + 'be shorter.'\n }\n if (/\\./.test(username)) {\n suffix = 'Each account segment should '\n }\n const ref = username.split('.')\n const len = ref.length\n for (let i = 0; i < len; i++) {\n const label = ref[i]\n if (!/^[a-z]/.test(label)) {\n return suffix + 'start with a lowercase letter.'\n }\n if (!/^[a-z0-9-]*$/.test(label)) {\n return suffix + 'have only lowercase letters, digits, or dashes.'\n }\n if (!/[a-z0-9]$/.test(label)) {\n return suffix + 'end with a lowercase letter or digit.'\n }\n if (label.length < 3) {\n return suffix + 'be longer.'\n }\n }\n return null\n}\n\nexport const operations = {\n vote: 0,\n comment: 1,\n transfer: 2,\n transfer_to_vesting: 3,\n withdraw_vesting: 4,\n limit_order_create: 5,\n limit_order_cancel: 6,\n feed_publish: 7,\n convert: 8,\n account_create: 9,\n account_update: 10,\n witness_update: 11,\n account_witness_vote: 12,\n account_witness_proxy: 13,\n pow: 14,\n custom: 15,\n report_over_production: 16,\n delete_comment: 17,\n custom_json: 18,\n comment_options: 19,\n set_withdraw_vesting_route: 20,\n limit_order_create2: 21,\n claim_account: 22,\n create_claimed_account: 23,\n request_account_recovery: 24,\n recover_account: 25,\n change_recovery_account: 26,\n escrow_transfer: 27,\n escrow_dispute: 28,\n escrow_release: 29,\n pow2: 30,\n escrow_approve: 31,\n transfer_to_savings: 32,\n transfer_from_savings: 33,\n cancel_transfer_from_savings: 34,\n custom_binary: 35,\n decline_voting_rights: 36,\n reset_account: 37,\n set_reset_account: 38,\n claim_reward_balance: 39,\n delegate_vesting_shares: 40,\n account_create_with_delegation: 41,\n witness_set_properties: 42,\n account_update2: 43,\n create_proposal: 44,\n update_proposal_votes: 45,\n remove_proposal: 46,\n update_proposal: 47,\n collateralized_convert: 48,\n recurrent_transfer: 49,\n // virtual ops\n fill_convert_request: 50,\n author_reward: 51,\n curation_reward: 52,\n comment_reward: 53,\n liquidity_reward: 54,\n interest: 55,\n fill_vesting_withdraw: 56,\n fill_order: 57,\n shutdown_witness: 58,\n fill_transfer_from_savings: 59,\n hardfork: 60,\n comment_payout_update: 61,\n return_vesting_delegation: 62,\n comment_benefactor_reward: 63,\n producer_reward: 64,\n clear_null_account_balance: 65,\n proposal_pay: 66,\n sps_fund: 67,\n hardfork_hive: 68,\n hardfork_hive_restore: 69,\n delayed_voting: 70,\n consolidate_treasury_balance: 71,\n effective_comment_vote: 72,\n ineffective_delete_comment: 73,\n sps_convert: 74,\n expired_account_notification: 75,\n changed_recovery_account: 76,\n transfer_to_vesting_completed: 77,\n pow_reward: 78,\n vesting_shares_split: 79,\n account_created: 80,\n fill_collateralized_convert_request: 81,\n system_warning: 82,\n fill_recurrent_transfer: 83,\n failed_recurrent_transfer: 84,\n limit_order_cancelled: 85,\n producer_missed: 86,\n proposal_fee: 87,\n collateralized_convert_immediate_conversion: 88,\n escrow_approved: 89,\n escrow_rejected: 90,\n proxy_cleared: 91,\n declined_voting_rights: 92\n}\n\n/**\n * Make bitmask filter to be used with get_account_history call\n */\nexport const makeBitMaskFilter = (allowedOperations: number[]): [string | null, string | null] => {\n return allowedOperations\n .reduce(reduceFunction, [BigInt(0), BigInt(0)])\n .map((value: bigint) => (value !== BigInt(0) ? value.toString() : null)) as [string | null, string | null]\n}\nconst reduceFunction = (\n [low, high]: [bigint, bigint],\n allowedOperation: number\n): [bigint, bigint] => {\n if (allowedOperation < 64) {\n return [low | (BigInt(1) << BigInt(allowedOperation)), high]\n } else {\n return [low, high | (BigInt(1) << BigInt(allowedOperation - 64))]\n }\n}\n\nexport const buildWitnessSetProperties = (\n owner: string,\n props: WitnessProps\n): ['witness_set_properties', { extensions: never[]; owner: string; props: any }] => {\n const data = {\n extensions: [],\n owner,\n props: []\n }\n for (const key of Object.keys(props)) {\n if ((props as any)[key] === undefined) continue\n let type\n switch (key) {\n case 'key':\n case 'new_signing_key':\n type = Serializer.PublicKey\n break\n case 'account_subsidy_budget':\n case 'account_subsidy_decay':\n case 'maximum_block_size':\n type = Serializer.UInt32\n break\n case 'hbd_interest_rate':\n type = Serializer.UInt16\n break\n case 'url':\n type = Serializer.String\n break\n case 'hbd_exchange_rate':\n type = Serializer.Price\n break\n case 'account_creation_fee':\n type = Serializer.Asset\n break\n default:\n throw new Error(`Unknown witness prop: ${key}`)\n }\n data.props.push([key, serialize(type, props[key])])\n }\n data.props.sort((a: any, b: any) => a[0].localeCompare(b[0]))\n return ['witness_set_properties', data]\n}\n\nconst serialize = (serializer: any, data: any) => {\n const buffer = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)\n serializer(buffer, data)\n buffer.flip()\n // `props` values must be hex\n return bytesToHex(new Uint8Array(buffer.toBuffer()))\n}\n","/**\n * Re-exports hive-tx APIs and provides helper functions that bridge\n * API differences from the legacy dhive library.\n */\n\nimport {\n PrivateKey,\n Transaction,\n callRPCBroadcast,\n type BroadcastResult,\n} from \"../../hive-tx\";\nimport type { Operation, OperationName, OperationBody } from \"../../hive-tx\";\nimport { sha256 as nobleSha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Re-exports ─────────────────────────────────────────────────────────────\n\nexport {\n Transaction as HiveTxTransaction,\n PrivateKey,\n PublicKey,\n Signature,\n Memo,\n config as hiveTxConfig,\n callRPC,\n callRPCBroadcast,\n callREST,\n callWithQuorum,\n utils as hiveTxUtils,\n} from \"../../hive-tx\";\n\nexport type {\n Operation,\n OperationName,\n OperationBody,\n AssetSymbol,\n BroadcastResult,\n AccountCreateOperation,\n CustomJsonOperation,\n // Referenced in ConfigManager.setResilience's public signature — must be\n // nameable from the main entry, not only from @ecency/sdk/hive.\n ResilienceOptions,\n} from \"../../hive-tx\";\n\n// ── Compat types (matching dhive shapes used throughout the codebase) ──────\n\n/** Compatible with dhive's TransactionConfirmation from broadcast_transaction_synchronous */\nexport interface TransactionConfirmation {\n id: string;\n block_num: number;\n trx_num: number;\n expired: boolean;\n}\n\n/** Authority role type used in key management */\nexport type AuthorityType = \"owner\" | \"active\" | \"posting\" | \"memo\";\n\n/** SMT asset format (NAI representation) used in transaction history */\nexport interface SMTAsset {\n amount: string;\n precision: number;\n nai: string;\n}\n\n/** RC account data from rc_api.find_rc_accounts */\nexport interface RCAccount {\n account: string;\n rc_manabar: {\n current_mana: string | number;\n last_update_time: number;\n };\n max_rc: string | number;\n max_rc_creation_adjustment: {\n amount: string;\n precision: number;\n nai: string;\n };\n delegated_rc: number;\n received_delegated_rc: number;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * Compute SHA-256 hash of a string or Uint8Array.\n * Drop-in replacement for dhive's `cryptoUtils.sha256()`.\n */\nexport function sha256(input: string | Uint8Array): Uint8Array {\n let data: Uint8Array;\n if (typeof input === \"string\") {\n // Inline UTF-8 encode — avoids TextEncoder which is unavailable on some\n // runtimes (React Native / Hermes).\n const bytes: number[] = [];\n for (let i = 0; i < input.length; i++) {\n let c = input.charCodeAt(i);\n if (c < 0x80) {\n bytes.push(c);\n } else if (c < 0x800) {\n bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < input.length) {\n const next = input.charCodeAt(++i);\n c = 0x10000 + ((c & 0x3ff) << 10) + (next & 0x3ff);\n bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n data = new Uint8Array(bytes);\n } else {\n data = input;\n }\n return nobleSha256(data);\n}\n\n/** Check if a string is a valid WIF-encoded private key. */\nexport function isWif(key: string): boolean {\n try {\n PrivateKey.fromString(key);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Sign and broadcast operations, returning a dhive-compatible TransactionConfirmation.\n *\n * Uses broadcast_transaction_synchronous so the response includes block_num/trx_num,\n * matching the shape that the rest of the codebase expects from dhive's\n * `client.broadcast.sendOperations()`.\n *\n * @deprecated Prefer {@link broadcastOperationsAsync} (the default for\n * `useBroadcastMutation`); poll `transaction_status_api` if you need block\n * confirmation. Kept only for explicit `broadcastMode: 'sync'` opt-ins.\n */\nexport async function broadcastOperations(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return callRPCBroadcast(\"condenser_api.broadcast_transaction_synchronous\", [\n tx.transaction,\n ]);\n}\n\n/**\n * Sign and broadcast operations without waiting for block inclusion.\n *\n * Uses broadcast_transaction which returns as soon as the node accepts the\n * transaction into its mempool. Transport and RPC errors (network failures,\n * invalid operations, expired transactions) are still thrown immediately -\n * the only thing skipped is the wait for the transaction to appear in a block.\n *\n * Returns { tx_id, status: 'unknown' }. To confirm block inclusion afterward,\n * poll transaction_status_api with the returned tx_id.\n *\n * Prefer this for operations where faster response matters more than\n * immediate confirmation (e.g. votes, reblogs, follows).\n *\n * Use broadcastOperations() when you need block_num/trx_num confirmation\n * (e.g. transfers, account updates, key changes).\n */\nexport async function broadcastOperationsAsync(\n ops: Operation[],\n key: PrivateKey\n): Promise {\n const tx = new Transaction();\n for (const op of ops) {\n await tx.addOperation(\n op[0] as OperationName,\n op[1] as OperationBody\n );\n }\n tx.sign(key);\n return tx.broadcast(false);\n}\n\n// ── Mana calculations (ported from dhive's RCAPI) ──────────────────────────\n\ninterface Manabar {\n current_mana: string | number;\n last_update_time: number;\n}\n\ninterface ManaResult {\n current_mana: number;\n max_mana: number;\n percentage: number;\n}\n\nconst MANA_REGENERATION_SECONDS = 432000; // 5 days\n\nfunction calculateManabar(maxMana: number, manabar: Manabar): ManaResult {\n const delta = Date.now() / 1000 - manabar.last_update_time;\n let currentMana =\n Number(manabar.current_mana) +\n (delta * maxMana) / MANA_REGENERATION_SECONDS;\n let percentage = Math.round((currentMana / maxMana) * 10000);\n if (!isFinite(percentage) || percentage < 0) {\n percentage = 0;\n } else if (percentage > 10000) {\n percentage = 10000;\n }\n return { current_mana: currentMana, max_mana: maxMana, percentage };\n}\n\n/**\n * Get effective vesting shares for an account (matching dhive's getVests).\n * Subtracts delegated, adds received, accounts for pending withdrawals.\n */\nfunction getVests(account: any): number {\n const vests = parseFloat(account.vesting_shares);\n const delegated = parseFloat(account.delegated_vesting_shares);\n const received = parseFloat(account.received_vesting_shares);\n const withdrawRate = parseFloat(account.vesting_withdraw_rate);\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n return vests - withdrawVests - delegated + received;\n}\n\n/** Calculate voting power mana (equivalent to dhive client.rc.calculateVPMana) */\nexport function calculateVPMana(account: any): ManaResult {\n const maxMana = getVests(account) * 1e6;\n return calculateManabar(maxMana, account.voting_manabar);\n}\n\n/** Calculate RC mana (equivalent to dhive client.rc.calculateRCMana) */\nexport function calculateRCMana(rcAccount: RCAccount): ManaResult {\n return calculateManabar(\n Number(rcAccount.max_rc),\n rcAccount.rc_manabar\n );\n}\n\n// setHiveTxNodes and initHiveTx removed — config is now unified.\n// Use hiveTxConfig directly or ConfigManager.setHiveNodes().\n","/**\n * Chain error handling utilities\n * Extracted from web's operations.ts and mobile's dhive.ts error handling patterns\n */\n\nexport enum ErrorType {\n COMMON = \"common\",\n INFO = \"info\",\n INSUFFICIENT_RESOURCE_CREDITS = \"insufficient_resource_credits\",\n MISSING_AUTHORITY = \"missing_authority\",\n TOKEN_EXPIRED = \"token_expired\",\n NETWORK = \"network\",\n TIMEOUT = \"timeout\",\n VALIDATION = \"validation\",\n}\n\nexport interface ParsedChainError {\n message: string;\n type: ErrorType;\n originalError?: any;\n}\n\n/**\n * Parses Hive blockchain errors into standardized format.\n * Extracted from web's operations.ts and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string from a blockchain operation\n * @returns Parsed error with user-friendly message and categorized type\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * const parsed = parseChainError(error);\n * console.log(parsed.message); // \"Insufficient Resource Credits. Please wait or power up.\"\n * console.log(parsed.type); // ErrorType.INSUFFICIENT_RESOURCE_CREDITS\n * }\n * ```\n */\nexport function parseChainError(error: any): ParsedChainError {\n // Extract error strings from various error formats\n // Check both error_description and message independently for pattern matching\n const errorDescription = error?.error_description ? String(error.error_description) : '';\n const errorMessage = error?.message ? String(error.message) : '';\n // HiveSigner throws plain objects like { error: \"unauthorized\", error_description: \"...\" }\n const errorCode = error?.error ? String(error.error) : '';\n const errorString = errorDescription || errorMessage || String(error || '');\n\n // Helper function to test patterns against all error fields\n const testPattern = (pattern: RegExp): boolean => {\n // Check error code first (e.g. HiveSigner's { error: \"unauthorized\" })\n if (errorCode && pattern.test(errorCode)) return true;\n // Check error_description (priority)\n if (errorDescription && pattern.test(errorDescription)) return true;\n // Then check message\n if (errorMessage && pattern.test(errorMessage)) return true;\n // Finally check fallback errorString (handles plain string inputs)\n if (errorString && pattern.test(errorString)) return true;\n return false;\n };\n\n // Resource credits (from both web and mobile patterns)\n if (\n testPattern(/please wait to transact/i) ||\n testPattern(/insufficient rc/i) ||\n testPattern(/rc mana|rc account|resource credits/i)\n ) {\n return {\n message: \"Insufficient Resource Credits. Please wait or power up.\",\n type: ErrorType.INSUFFICIENT_RESOURCE_CREDITS,\n originalError: error,\n };\n }\n\n // Min comment interval (from web operations.ts line 29)\n if (testPattern(/you may only post once every/i)) {\n return {\n message: \"Please wait before posting again (minimum 3 second interval between comments).\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Identical vote (from web operations.ts line 31)\n if (testPattern(/your current vote on this comment is identical/i)) {\n return {\n message: \"You have already voted with the same weight.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Must claim something (from web operations.ts line 33)\n if (testPattern(/must claim something/i)) {\n return {\n message: \"You must claim rewards before performing this action.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot claim that much VESTS (from web operations.ts line 35)\n if (testPattern(/cannot claim that much vests/i)) {\n return {\n message: \"Cannot claim that amount. Please check your pending rewards.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Cannot delete comment with positive votes (from web operations.ts line 42)\n if (testPattern(/cannot delete a comment with net positive/i)) {\n return {\n message: \"Cannot delete a comment with positive votes.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Comment has children (from web operations.ts line 44)\n if (testPattern(/children == 0/i)) {\n return {\n message: \"Cannot delete a comment with replies.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Comment already paid out (from web operations.ts line 46)\n if (testPattern(/comment_cashout/i)) {\n return {\n message: \"Cannot modify a comment that has already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Voting on paid out post (from web operations.ts line 48)\n if (testPattern(/votes evaluating for comment that is paid out is forbidden/i)) {\n return {\n message: \"Cannot vote on posts that have already been paid out.\",\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // No key available (SDK internal - from broadcastWithMethod when key not stored)\n if (testPattern(/no (active|owner|posting|memo) key available/i)) {\n return {\n message: \"Key not available. Please provide your key to sign this operation.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing active authority. Hive nodes return \"missing required active\n // authority\"; web operations.ts also throws the short form. Match both so the\n // auth fallback (auth-upgrade dialog) fires instead of misclassifying as a\n // generic chain error.\n if (testPattern(/missing (required )?active authority/i)) {\n return {\n message: \"Missing active authority. This operation requires your active key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing owner authority (\"missing required owner authority\" or short form)\n if (testPattern(/missing (required )?owner authority/i)) {\n return {\n message: \"Missing owner authority. This operation requires your owner key.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Missing posting authority (general pattern)\n if (testPattern(/missing (required )?posting authority/i)) {\n return {\n message: \"Missing posting authority. Please check your login method.\",\n type: ErrorType.MISSING_AUTHORITY,\n originalError: error,\n };\n }\n\n // Token expired / unauthorized (HiveSigner OAuth2 errors + general patterns)\n // HiveSigner returns: { error: \"invalid_grant\" } for invalid/expired tokens,\n // { error: \"unauthorized_access\" } for IP-based access denial\n if (\n errorCode === 'invalid_grant' ||\n errorCode === 'unauthorized_access' ||\n testPattern(/token expired/i) ||\n testPattern(/invalid token/i) ||\n testPattern(/\\bunauthorized\\b/i) ||\n testPattern(/\\bforbidden\\b/i)\n ) {\n return {\n message: \"Authentication token expired. Please log in again.\",\n type: ErrorType.TOKEN_EXPIRED,\n originalError: error,\n };\n }\n\n // Already reblogged\n if (testPattern(/has already reblogged/i) || testPattern(/already reblogged this post/i)) {\n return {\n message: \"You have already reblogged this post.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Duplicate transaction\n if (testPattern(/duplicate transaction/i)) {\n return {\n message: \"This transaction has already been processed.\",\n type: ErrorType.INFO,\n originalError: error,\n };\n }\n\n // Network errors (more specific patterns to avoid false positives)\n if (\n testPattern(/econnrefused/i) ||\n testPattern(/connection refused/i) ||\n testPattern(/failed to fetch/i) ||\n testPattern(/\\bnetwork[-\\s]?(request|error|timeout|unreachable|down|failed)\\b/i)\n ) {\n return {\n message: \"Network error. Please check your connection and try again.\",\n type: ErrorType.NETWORK,\n originalError: error,\n };\n }\n\n // Timeout errors\n if (testPattern(/timeout/i) || testPattern(/timed out/i)) {\n return {\n message: \"Request timed out. Please try again.\",\n type: ErrorType.TIMEOUT,\n originalError: error,\n };\n }\n\n // Account doesn't exist\n if (testPattern(/account.*does not exist/i) || testPattern(/account not found/i)) {\n return {\n message: \"Account not found. Please check the username.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Invalid memo key\n if (testPattern(/invalid memo key/i)) {\n return {\n message: \"Invalid memo key. Cannot encrypt message.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Insufficient funds (require both words in same string to avoid cross-field false positives)\n if (testPattern(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i)) {\n return {\n message: \"Insufficient funds for this transaction.\",\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Generic validation errors (use word boundaries to be more specific)\n if (testPattern(/\\b(invalid|validation)\\b/i)) {\n // Truncate to 150 chars like other branches\n const message = (error?.message || errorString).substring(0, 150) || \"Validation error occurred\";\n return {\n message,\n type: ErrorType.VALIDATION,\n originalError: error,\n };\n }\n\n // Default: return original error message\n // Check for error_description first (from web operations.ts line 65-72)\n if (error?.error_description && typeof error.error_description === \"string\") {\n return {\n message: error.error_description.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Then check message field\n if (error?.message && typeof error.message === \"string\") {\n return {\n message: error.message.substring(0, 150),\n type: ErrorType.COMMON,\n originalError: error,\n };\n }\n\n // Handle plain objects without message property (avoid \"[object Object]\")\n let message: string;\n if (typeof error === 'object' && error !== null) {\n // Check for common error properties\n if (error.error_description) {\n message = String(error.error_description);\n } else if (error.code) {\n message = `Error code: ${error.code}`;\n } else if (errorString && errorString !== '[object Object]') {\n message = errorString.substring(0, 150);\n } else {\n message = \"Unknown error occurred\";\n }\n } else {\n message = errorString.substring(0, 150) || \"Unknown error occurred\";\n }\n\n return {\n message,\n type: ErrorType.COMMON,\n originalError: error,\n };\n}\n\n/**\n * Formats error for display to user.\n * Returns tuple of [message, type] for backward compatibility with existing code.\n *\n * This function maintains compatibility with the old formatError signature from\n * web's operations.ts (line 59-84) and mobile's dhive.ts error handling.\n *\n * @param error - The error object or string\n * @returns Tuple of [user-friendly message, error type]\n *\n * @example\n * ```typescript\n * try {\n * await transfer(...);\n * } catch (error) {\n * const [message, type] = formatError(error);\n * showToast(message, type);\n * }\n * ```\n */\nexport function formatError(error: any): [string, ErrorType] {\n const parsed = parseChainError(error);\n return [parsed.message, parsed.type];\n}\n\n/**\n * Checks if error indicates missing authority and should trigger auth fallback.\n * Used by the SDK's useBroadcastMutation to determine if it should retry with\n * an alternate authentication method.\n *\n * @param error - The error object or string\n * @returns true if auth fallback should be attempted\n *\n * @example\n * ```typescript\n * try {\n * await broadcast(operations);\n * } catch (error) {\n * if (shouldTriggerAuthFallback(error)) {\n * // Try with alternate auth method\n * await broadcastWithHiveAuth(operations);\n * }\n * }\n * ```\n */\nexport function shouldTriggerAuthFallback(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.MISSING_AUTHORITY || type === ErrorType.TOKEN_EXPIRED;\n}\n\n/**\n * Checks if error is a resource credits (RC) error.\n * Useful for showing specific UI feedback about RC issues.\n *\n * @param error - The error object or string\n * @returns true if the error is related to insufficient RC\n *\n * @example\n * ```typescript\n * try {\n * await vote(...);\n * } catch (error) {\n * if (isResourceCreditsError(error)) {\n * showRCWarning(); // Show specific RC education/power up UI\n * }\n * }\n * ```\n */\nexport function isResourceCreditsError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INSUFFICIENT_RESOURCE_CREDITS;\n}\n\n/**\n * Checks if error is informational (not critical).\n * Informational errors typically don't need retry logic.\n *\n * @param error - The error object or string\n * @returns true if the error is informational\n */\nexport function isInfoError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.INFO;\n}\n\n/**\n * Checks if error is network-related and should be retried.\n *\n * @param error - The error object or string\n * @returns true if the error is network-related\n */\nexport function isNetworkError(error: any): boolean {\n const { type } = parseChainError(error);\n return type === ErrorType.NETWORK || type === ErrorType.TIMEOUT;\n}\n","import {\n useMutation,\n type MutationKey,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { PrivateKey, RPCError } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { broadcastOperations, broadcastOperationsAsync, type TransactionConfirmation } from \"@/modules/core/hive-tx\";\nimport type { BroadcastResult } from \"../../../hive-tx\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { shouldTriggerAuthFallback } from \"@/modules/core/errors\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport hs from \"hivesigner\";\n\n/**\n * Broadcast mode controls whether the SDK waits for block inclusion.\n *\n * - `'async'` (default): Uses `broadcast_transaction` — returns once the node\n * accepts the transaction into its mempool. Transport and RPC errors are\n * still thrown immediately; only the block-inclusion wait is skipped.\n *\n * - `'sync'`: Uses `broadcast_transaction_synchronous` — waits for block\n * inclusion and returns `block_num`/`trx_num`. Deprecated; prefer `'async'`\n * and poll `transaction_status_api` if you need block confirmation.\n */\nexport type BroadcastMode = 'sync' | 'async';\n\n/**\n * Broadcasts operations using a specific auth method.\n *\n * @param method - Auth method to use ('key', 'hiveauth', 'hivesigner', 'keychain', 'custom')\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and configuration\n * @param authority - Key authority to use (posting, active, owner, or memo)\n * @param fetchedKey - Optional pre-fetched key to avoid duplicate fetches\n * @param fetchedToken - Optional pre-fetched access token to avoid duplicate fetches\n * @param broadcastMode - Whether to wait for block inclusion ('sync') or just mempool acceptance ('async')\n * @returns Transaction confirmation from the blockchain\n * @throws Error if method is not available or broadcast fails\n */\nasync function broadcastWithMethod(\n method: string,\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n fetchedKey?: string | null,\n fetchedToken?: string | null,\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n switch (method) {\n case 'key': {\n if (!adapter) {\n throw new Error('No adapter provided for key-based auth');\n }\n\n // Use pre-fetched key if provided, otherwise fetch it\n let key: string | null | undefined = fetchedKey;\n\n if (key === undefined) {\n // Key not pre-fetched, fetch it now based on authority\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n } else {\n throw new Error(\n `Owner key not supported by adapter. Owner operations (like account recovery) ` +\n `require master password login or manual key entry.`\n );\n }\n break;\n\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n } else {\n throw new Error(\n `Memo key not supported by adapter. Use memo encryption methods instead.`\n );\n }\n break;\n\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n }\n\n if (!key) {\n throw new Error(`No ${authority} key available for ${username}`);\n }\n\n // Attempt broadcast with key\n const privateKey = PrivateKey.fromString(key);\n if (broadcastMode === 'async') {\n return await broadcastOperationsAsync(ops, privateKey);\n }\n return await broadcastOperations(ops, privateKey);\n }\n\n case 'hiveauth': {\n if (!adapter?.broadcastWithHiveAuth) {\n throw new Error('HiveAuth not supported by adapter');\n }\n return await adapter.broadcastWithHiveAuth(username, ops, authority);\n }\n\n case 'hivesigner': {\n if (!adapter) {\n throw new Error('No adapter provided for HiveSigner auth');\n }\n\n // Access tokens only have posting authority — for active/owner/memo ops,\n // go directly to platform-specific HiveSigner broadcast (e.g., redirect to hivesigner.com)\n if (authority !== 'posting') {\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw new Error(`HiveSigner access token cannot sign ${authority} operations. No platform broadcast available.`);\n }\n\n // Try direct API broadcast with access token first (posting ops only)\n const token = fetchedToken !== undefined\n ? fetchedToken\n : await adapter.getAccessToken(username);\n\n if (token) {\n try {\n const client = new hs.Client({ accessToken: token });\n const response = await client.broadcast(ops);\n return response.result;\n } catch (tokenError) {\n // Token broadcast failed — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner && shouldTriggerAuthFallback(tokenError)) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n throw tokenError;\n }\n }\n\n // No token available — try platform-specific HiveSigner broadcast\n if (adapter.broadcastWithHiveSigner) {\n return await adapter.broadcastWithHiveSigner(username, ops, authority);\n }\n\n throw new Error(`No access token available for ${username}`);\n }\n\n case 'keychain': {\n if (!adapter?.broadcastWithKeychain) {\n throw new Error('Keychain not supported by adapter');\n }\n return await adapter.broadcastWithKeychain(username, ops, authority);\n }\n\n case 'custom': {\n if (!auth?.broadcast) {\n throw new Error('No custom broadcast function provided');\n }\n return (await auth.broadcast(ops, authority)) as TransactionConfirmation;\n }\n\n default:\n throw new Error(`Unknown auth method: ${method}`);\n }\n}\n\n/**\n * Attempts to broadcast operations using multiple auth methods in fallback chain.\n * Implements sophisticated fallback pattern from mobile app.\n *\n * @param username - Hive username to broadcast for\n * @param ops - Operations to broadcast\n * @param auth - AuthContextV2 with adapter and fallback configuration\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n * @returns Transaction confirmation from the blockchain\n * @throws Error if all auth methods fail or if a non-auth error occurs\n *\n * @remarks\n * **Preferred Behavior (when adapter.getLoginType exists):**\n * - Calls adapter.getLoginType() to determine user's actual auth method\n * - Uses ONLY that method (no fallbacks) - more predictable and faster\n * - If it fails, throws the error immediately\n *\n * **Fallback Behavior (for backward compatibility):**\n * - Tries each auth method in the fallback chain order\n * - Only continues to next method if error is auth-related (missing authority, token expired)\n * - Stops immediately for non-auth errors (RC exhaustion, network errors, validation errors)\n * - Collects all errors and provides detailed failure message\n *\n * @example\n * ```typescript\n * // Preferred: Adapter with getLoginType (single method, no fallbacks)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter, // includes getLoginType()\n * };\n *\n * // Legacy: Explicit fallback chain (tries multiple methods)\n * const auth: AuthContextV2 = {\n * adapter: myAdapter,\n * fallbackChain: ['key', 'hiveauth', 'hivesigner'],\n * };\n * ```\n */\nasync function broadcastWithFallback(\n username: string,\n ops: Operation[],\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n broadcastMode: BroadcastMode = 'async'\n): Promise {\n const adapter = auth?.adapter;\n\n // PREFERRED APPROACH: If adapter provides getLoginType, use smart auth strategy\n // This avoids unnecessary fallback attempts and is more predictable\n if (adapter?.getLoginType) {\n const loginType = await adapter.getLoginType(username, authority);\n\n if (loginType) {\n // SMART AUTH STRATEGY: Optimize based on login type + authority + credentials\n\n // Check if user has granted ecency.app posting authority\n const hasPostingAuth = adapter.hasPostingAuthorization\n ? await adapter.hasPostingAuthorization(username)\n : false;\n\n // OPTIMIZATION: Use HiveSigner token for posting ops when posting auth is granted\n // This is faster than direct key signing or HiveAuth for key-based logins\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'key'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to direct key signing if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to key:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for keychain/MetaMask users with posting auth (faster, no popup)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'keychain'\n ) {\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n console.warn('[SDK] HiveSigner token auth failed, falling back to keychain/snap:', error);\n }\n }\n\n // OPTIMIZATION: Use HiveSigner token for HiveAuth users with posting auth (faster)\n if (\n authority === 'posting' &&\n hasPostingAuth &&\n loginType === 'hiveauth'\n ) {\n try {\n // Try HiveSigner API first (faster)\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Only fallback if this is an auth-related error\n // Otherwise, rethrow the original error (e.g., network errors, validation errors)\n if (!shouldTriggerAuthFallback(error)) {\n throw error;\n }\n // Fallback to HiveAuth if token auth method fails\n console.warn('[SDK] HiveSigner token auth failed, falling back to HiveAuth:', error);\n }\n }\n\n // Use user's actual login method\n try {\n return await broadcastWithMethod(loginType, username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (error) {\n // Check if error is due to missing authority (e.g., posting key trying active op)\n if (shouldTriggerAuthFallback(error)) {\n // Show auth upgrade UI if available (only for posting/active operations)\n if (\n adapter.showAuthUpgradeUI &&\n (authority === 'posting' || authority === 'active')\n ) {\n // Guard against empty operations array\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n\n // User selected a specific method - delegate to broadcastWithMethod\n // This handles all auth methods (hiveauth, hivesigner, key, keychain, custom, etc.)\n // broadcastWithMethod already contains all necessary validation and method-specific logic\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // Not an auth error, or no upgrade UI available - throw original error\n throw error;\n }\n }\n\n // loginType is null — user's auth method is unknown (e.g., incomplete login data)\n if (authority === 'posting') {\n // For posting ops, try HiveSigner — access token is usually available for all logins\n try {\n return await broadcastWithMethod('hivesigner', username, ops, auth, authority, undefined, undefined, broadcastMode);\n } catch (hsError) {\n if (shouldTriggerAuthFallback(hsError) && adapter.showAuthUpgradeUI) {\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`No login type available for ${username}. Please log in again.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n throw hsError;\n }\n } else if (authority === 'active' && adapter.showAuthUpgradeUI) {\n // For active ops, show auth upgrade dialog — no silent fallback possible\n const operationName = ops.length > 0 ? ops[0][0] : 'unknown';\n const selectedMethod = await adapter.showAuthUpgradeUI(authority, operationName);\n if (!selectedMethod) {\n throw new Error(`Operation requires ${authority} authority. User declined alternate auth.`);\n }\n return await broadcastWithMethod(selectedMethod, username, ops, auth, authority, undefined, undefined, broadcastMode);\n }\n }\n\n // FALLBACK APPROACH: For backward compatibility, use fallback chain\n // This is only used if adapter doesn't provide getLoginType\n const chain = auth?.fallbackChain ?? ['key', 'hiveauth', 'hivesigner', 'keychain', 'custom'];\n const errors: Map = new Map();\n\n for (const method of chain) {\n try {\n // Check if method is available before attempting\n let shouldSkip = false;\n let skipReason = '';\n let prefetchedKey: string | null | undefined;\n let prefetchedToken: string | null | undefined;\n\n switch (method) {\n case 'key':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch key to check availability (will be reused in broadcast)\n let key: string | null | undefined;\n\n switch (authority) {\n case 'owner':\n if (adapter.getOwnerKey) {\n key = await adapter.getOwnerKey(username);\n }\n break;\n case 'active':\n if (adapter.getActiveKey) {\n key = await adapter.getActiveKey(username);\n }\n break;\n case 'memo':\n if (adapter.getMemoKey) {\n key = await adapter.getMemoKey(username);\n }\n break;\n case 'posting':\n default:\n key = await adapter.getPostingKey(username);\n break;\n }\n\n if (!key) {\n shouldSkip = true;\n skipReason = `No ${authority} key available`;\n } else {\n prefetchedKey = key; // Store for reuse\n }\n }\n break;\n case 'hiveauth':\n if (!adapter?.broadcastWithHiveAuth) {\n shouldSkip = true;\n skipReason = 'HiveAuth not supported by adapter';\n }\n break;\n case 'hivesigner':\n if (!adapter) {\n shouldSkip = true;\n skipReason = 'No adapter provided';\n } else {\n // Pre-fetch token if available (will be reused in broadcast)\n const token = await adapter.getAccessToken(username);\n if (token) {\n prefetchedToken = token; // Store for reuse\n }\n // When no token but adapter exists, don't skip —\n // broadcastWithMethod can fall back to adapter.broadcastWithHiveSigner\n }\n break;\n case 'keychain':\n if (!adapter?.broadcastWithKeychain) {\n shouldSkip = true;\n skipReason = 'Keychain not supported by adapter';\n }\n break;\n case 'custom':\n if (!auth?.broadcast) {\n shouldSkip = true;\n skipReason = 'No custom broadcast function provided';\n }\n break;\n }\n\n if (shouldSkip) {\n errors.set(method, new Error(`Skipped: ${skipReason}`));\n continue;\n }\n\n // Method is available, attempt broadcast with pre-fetched credentials\n return await broadcastWithMethod(method, username, ops, auth, authority, prefetchedKey, prefetchedToken, broadcastMode);\n } catch (error) {\n // Record actual error from failed broadcast attempt\n errors.set(method, error as Error);\n\n // Only continue fallback if error suggests trying another method\n if (!shouldTriggerAuthFallback(error)) {\n // If it's not an auth error, throw immediately (e.g., RC error, network error)\n throw error;\n }\n }\n }\n\n // FIX #2: Improved error message distinguishes between skips and real failures\n const hasRealAttempts = Array.from(errors.values()).some(\n error => !error.message.startsWith('Skipped:')\n );\n\n if (!hasRealAttempts) {\n // All methods were skipped (none attempted)\n const skipReasons = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n throw new Error(\n `[SDK][Broadcast] No auth methods attempted for ${username}. ${skipReasons}`\n );\n }\n\n // At least one method was attempted but all failed\n const errorMessages = Array.from(errors.entries())\n .map(([method, error]) => `${method}: ${error.message}`)\n .join(', ');\n\n throw new Error(\n `[SDK][Broadcast] All auth methods failed for ${username}. Errors: ${errorMessages}`\n );\n}\n\n/**\n * React Query mutation hook for broadcasting Hive operations.\n * Supports multiple authentication methods with automatic fallback.\n *\n * @template T - Type of the mutation payload\n * @param mutationKey - React Query mutation key for cache management\n * @param username - Hive username (required for broadcast)\n * @param operations - Function that converts payload to Hive operations\n * @param onSuccess - Success callback after broadcast completes\n * @param auth - Authentication context (supports both legacy AuthContext and new AuthContextV2)\n * @param authority - Key authority to use ('posting' | 'active' | 'owner' | 'memo'), defaults to 'posting'\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Authentication Flow:**\n *\n * 1. **With AuthContextV2 + adapter + enableFallback** (recommended for new code):\n * - Tries auth methods in fallbackChain order\n * - Smart fallback: only retries on auth errors, not RC/network errors\n * - Uses platform adapter for storage, UI, and broadcasting\n *\n * 2. **With legacy AuthContext** (backward compatible):\n * - Tries auth.broadcast() first (custom implementation)\n * - Falls back to postingKey if available\n * - Falls back to accessToken (HiveSigner) if available\n * - Throws if no auth method available\n *\n * **Backward Compatibility:**\n * - All existing code using AuthContext will continue to work\n * - AuthContextV2 extends AuthContext, so it's a drop-in replacement\n * - enableFallback defaults to false if no adapter provided\n *\n * @example\n * ```typescript\n * // New pattern with platform adapter and fallback\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * },\n * 'posting'\n * );\n *\n * // Legacy pattern (still works)\n * const mutation = useBroadcastMutation(\n * ['vote'],\n * username,\n * (payload) => [voteOperation(payload)],\n * () => console.log('Success!'),\n * { postingKey: 'wif-key' }\n * );\n * ```\n */\nexport function useBroadcastMutation(\n mutationKey: MutationKey = [],\n username: string | undefined,\n operations: (payload: T) => Operation[],\n onSuccess: UseMutationOptions[\"onSuccess\"] = () => {},\n auth?: AuthContextV2,\n authority: AuthorityLevel = 'posting',\n options?: {\n onMutate?: UseMutationOptions[\"onMutate\"];\n onError?: UseMutationOptions[\"onError\"];\n onSettled?: UseMutationOptions[\"onSettled\"];\n /**\n * Controls whether to wait for block inclusion or just mempool acceptance.\n *\n * - `'async'` (default): Returns after mempool acceptance. Recommended for\n * all operations; errors are still thrown immediately.\n *\n * - `'sync'`: Waits for block inclusion, returns block_num/trx_num.\n * Deprecated; prefer `'async'`.\n */\n broadcastMode?: BroadcastMode;\n }\n) {\n const broadcastMode = options?.broadcastMode ?? 'async';\n\n return useMutation({\n onSuccess,\n onMutate: options?.onMutate,\n onError: options?.onError,\n onSettled: options?.onSettled,\n mutationKey: [...mutationKey, username],\n mutationFn: async (payload: T) => {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n\n const ops = operations(payload);\n\n try {\n // New: Try auth methods in fallback chain (if enabled)\n if (auth?.enableFallback !== false && auth?.adapter) {\n return await broadcastWithFallback(username, ops, auth, authority, broadcastMode);\n }\n\n // Legacy behavior: try methods in fixed order (backward compatible)\n if (auth?.broadcast) {\n return await auth.broadcast(ops, authority);\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n // Legacy auth only supports posting authority\n if (authority !== 'posting') {\n throw new Error(\n `[SDK][Broadcast] Legacy auth only supports posting authority, but '${authority}' was requested. ` +\n `Use AuthContextV2 with an adapter for ${authority} operations.`\n );\n }\n\n const privateKey = PrivateKey.fromString(postingKey);\n\n return await broadcastOperations(\n ops,\n privateKey\n );\n }\n\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const client = new hs.Client({ accessToken });\n const response = await client.broadcast(ops);\n return response.result;\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n } catch (e) {\n if (e instanceof RPCError) {\n // Normalize raw blockchain rejections (missing authority, RC exhaustion,\n // validation failures) from every broadcast path — sync and async — into\n // a plain Error whose message is preserved for downstream classification\n // (formatError), so React Query captures a handled mutation error.\n throw new Error(e.message);\n }\n throw e\n }\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport async function broadcastJson(\n username: string | undefined,\n id: string,\n payload: T,\n auth?: AuthContextV2\n) {\n if (!username) {\n throw new Error(\n \"[Core][Broadcast] Attempted to call broadcast API with anon user\"\n );\n }\n const jjson = {\n id,\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify(payload),\n };\n\n if (auth?.broadcast) {\n return auth.broadcast([[\"custom_json\", jjson]], \"posting\");\n }\n\n const postingKey = auth?.postingKey;\n if (postingKey) {\n const privateKey = PrivateKey.fromString(postingKey);\n\n return broadcastOperations(\n [[\"custom_json\", jjson]],\n privateKey\n );\n }\n\n // With hivesigner access token\n const accessToken = auth?.accessToken;\n if (accessToken) {\n const response = await new hs.Client({\n accessToken,\n }).customJson([], [username], id, JSON.stringify(payload));\n return response.result;\n }\n\n /*\n * Adapter, as a last resort rather than first.\n *\n * `auth.broadcast` above is the supported caller-supplied path inherited by\n * AuthContextV2, but the web app's `getSdkAuthContext` does not populate it.\n * A Keychain user whose posting key is not stored and who has no HiveSigner\n * token therefore reached the throw below instead of being asked to sign.\n * This is reachable today from follow and unfollow.\n *\n * Placed last on purpose: every branch above already works for the sessions\n * that reach it, and reordering would change which method signs for people\n * it currently serves. This only claims cases that were previously errors.\n */\n const adapter = auth?.adapter;\n if (adapter) {\n const ops: Parameters>[1] =\n [[\"custom_json\", jjson]];\n\n if (auth?.loginType === \"keychain\" && adapter.broadcastWithKeychain) {\n return adapter.broadcastWithKeychain(username, ops, \"posting\");\n }\n if (auth?.loginType === \"hiveauth\" && adapter.broadcastWithHiveAuth) {\n return adapter.broadcastWithHiveAuth(username, ops, \"posting\");\n }\n }\n\n throw new Error(\n \"[SDK][Broadcast] – cannot broadcast w/o posting key or token\"\n );\n}\n","import type { BroadcastMode } from \"./use-broadcast-mutation\";\nimport type { PlatformAdapter } from \"@/modules/core/types\";\n\n/**\n * Delay (ms) before invalidating chain-derived queries after an async\n * broadcast. ~1.3 Hive blocks (3s/block) so the just-broadcast transaction has\n * landed in a block before we refetch — otherwise the refetch returns pre-tx\n * state (e.g. a stale wallet balance).\n */\nexport const BROADCAST_INCLUSION_DELAY_MS = 4000;\n\n/**\n * Invalidate queries after a broadcast, accounting for broadcast mode.\n *\n * - `'sync'`: the transaction already waited for block inclusion, so refetch\n * immediately (returns the adapter's promise so callers may await it).\n * - `'async'` (default) / undefined: the transaction is only in the mempool, so\n * a refetch now would read pre-tx state — defer by ~1 block.\n *\n * No-ops when the adapter can't invalidate.\n */\nexport function invalidateAfterBroadcast(\n adapter: PlatformAdapter | null | undefined,\n broadcastMode: BroadcastMode | undefined,\n keys: any[][]\n): void | Promise {\n if (!adapter?.invalidateQueries) return;\n if (broadcastMode === \"sync\") {\n // Method call (not an extracted reference) so `this` stays bound to adapter.\n return adapter.invalidateQueries(keys);\n }\n setTimeout(() => adapter.invalidateQueries?.(keys), BROADCAST_INCLUSION_DELAY_MS);\n}\n","export function withTimeoutSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (!signal) return timeoutSignal;\n\n // AbortSignal.any is available in Chrome 116+, Safari 17.4+, Firefox 124+.\n // Fall back to manual AbortController wiring for older browsers.\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any([signal, timeoutSignal]);\n }\n\n const ac = new AbortController();\n const onAbort = () => {\n const reason = signal.aborted ? signal.reason : timeoutSignal.reason;\n ac.abort(reason);\n signal.removeEventListener(\"abort\", onAbort);\n timeoutSignal.removeEventListener(\"abort\", onAbort);\n };\n if (signal.aborted) {\n ac.abort(signal.reason);\n } else if (timeoutSignal.aborted) {\n ac.abort(timeoutSignal.reason);\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timeoutSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n return ac.signal;\n}\n","import { QueryClient } from \"@tanstack/react-query\";\nimport {\n config as hiveTxConfig,\n setNodes as setHiveTxNodes,\n setRestNodes as setHiveTxRestNodes,\n setRestNodesByApi as setHiveTxRestNodesByApi,\n setUserAgent as setHiveTxUserAgent,\n setResilience as setHiveTxResilience,\n type ResilienceOptions,\n} from \"../../hive-tx\";\nimport type { APIMethods } from \"../../hive-tx/api-types\";\n\n// Safe environment variable access for browser builds\n// In browser builds, tsup will replace process.env.* with literal values at compile time\nconst isDevelopment = (() => {\n try {\n return process.env?.NODE_ENV === 'development';\n } catch {\n return false;\n }\n})();\n\nconst getHeliusApiKey = () => {\n try {\n return process.env?.VITE_HELIUS_API_KEY;\n } catch {\n return undefined;\n }\n};\n\n/** Timeout for internal API calls (search, private API). */\nexport const INTERNAL_API_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on `gcTime` for any query that runs during SSR.\n *\n * A long window is fine in a browser or native app, where the cache holds one\n * user's data and lives as long as the session. It is not fine in a server\n * renderer: every query schedules a gc timer, a pending timer is a GC root, and\n * `Query` holds the whole `QueryCache` — so one long-lived entry keeps\n * everything else that request cached reachable for its entire window. A server\n * process then settles at roughly `ingest rate × gcTime`, which is how\n * ecency.com's renderers ended up aborting on the old-space cap rather than\n * levelling off (2026-07-26).\n *\n * Two minutes is far longer than any single render, which is the only window a\n * server-side entry has to be reused before it is dehydrated into the payload.\n *\n * Note this bounds SDK queries at the source. `apps/web` additionally clamps\n * every query through `defaultQueryOptions`, which is what protects it from\n * options defined outside the SDK; hosts that do not clamp get the right\n * behaviour from these defaults alone.\n */\nexport const SERVER_GC_TIME_MS = 2 * 60 * 1000;\n\n/**\n * How `CONFIG.queryClient` is resolved.\n *\n * This used to be a plain `queryClient: new QueryClient()` property — a single\n * instance created at module import and shared by every caller for the lifetime\n * of the process. That is correct in a browser (one process, one user) but wrong\n * under SSR, where one process serves every request: each server render wrote its\n * fetched data into that one cache and nothing ever removed it, so the heap grew\n * monotonically until the renderer hit its old-space limit and aborted.\n *\n * A host that renders on the server registers a resolver (see\n * `ConfigManager.setQueryClientResolver`) which returns the *current request's*\n * client, so cached data dies with the request that produced it. Hosts that\n * genuinely want one long-lived client keep using `setQueryClient`, and callers\n * that configure nothing fall back to a lazily created instance.\n *\n * The resolver is consulted on every read rather than cached here on purpose:\n * request scoping is the host's concern, and only the host can know when one\n * request ends and the next begins.\n */\nlet queryClientResolver: (() => QueryClient) | undefined;\n\n/** Created on first use, and only when no resolver has been registered. */\nlet fallbackQueryClient: QueryClient | undefined;\n\nfunction resolveQueryClient(): QueryClient {\n if (queryClientResolver) {\n return queryClientResolver();\n }\n return (fallbackQueryClient ??= new QueryClient());\n}\n\nexport const CONFIG = {\n privateApiHost: \"https://ecency.com\",\n /**\n * Observer used for bridge calls when nobody is logged in. The bridge applies\n * this account's mute list to the response, marking muted authors' posts and\n * comments `stats.gray` so clients can dim or collapse them. Anonymous\n * visitors therefore inherit Ecency's moderation instead of seeing an\n * unfiltered firehose. Apps may override via `ConfigManager.setDefaultObserver`,\n * which expects a real account rather than \"\" (see that setter).\n *\n * Note this only *marks* content: the bridge still returns muted authors'\n * posts, so an observer never shortens a feed.\n */\n defaultObserver: \"ecency\",\n /**\n * First-party client identifier sent as the `X-Ecency-Client` header on\n * search/private API requests. Lets the origin distinguish Ecency's own\n * web/mobile/SSR traffic from third-party integrators (who should use the\n * keyed api.hivesearcher.com backend instead of the public proxy). This is\n * a routing marker, not a secret. Apps may override via\n * `ConfigManager.setClientId` (e.g. \"web\" or \"mobile\") for observability.\n */\n clientId: \"ecency-sdk\",\n imageHost: \"https://i.ecency.com\",\n /** Current Hive RPC nodes. Reads from the unified hive-tx config. */\n get hiveNodes(): string[] {\n return hiveTxConfig.nodes;\n },\n heliusApiKey: getHeliusApiKey(),\n /**\n * The React Query client all SDK code reads through `getQueryClient()`.\n * Backed by a resolver so an SSR host can scope it per request — see the\n * `queryClientResolver` note above. Assigning replaces the resolver with one\n * that always returns the assigned client, preserving the previous\n * \"one client, set once\" behaviour for browser and native hosts.\n */\n get queryClient(): QueryClient {\n return resolveQueryClient();\n },\n set queryClient(client: QueryClient) {\n queryClientResolver = () => client;\n },\n pollsApiHost: \"https://poll.ecency.com\",\n plausibleHost: \"https://pl.ecency.com\",\n // DMCA filtering - can be configured by the app\n dmcaAccounts: [] as string[],\n dmcaTags: [] as string[],\n dmcaPatterns: [] as string[],\n // Pre-compiled regex patterns for performance and security\n dmcaTagRegexes: [] as RegExp[],\n dmcaPatternRegexes: [] as RegExp[],\n // Track if DMCA has been initialized to avoid duplicate logs\n _dmcaInitialized: false,\n};\n\ntype DmcaListsInput = {\n accounts?: string[];\n tags?: string[];\n posts?: string[];\n};\n\nexport namespace ConfigManager {\n export function setQueryClient(client: QueryClient) {\n CONFIG.queryClient = client;\n }\n\n /**\n * Register how the SDK should obtain its React Query client, for hosts where\n * a single shared instance is wrong — principally SSR, where one process\n * serves many requests and a shared cache both leaks memory and risks serving\n * one request's data to another.\n *\n * `resolve` is called on every SDK cache access and should return the client\n * belonging to the request currently being handled. In a Next.js App Router\n * host that means wrapping the factory in React's `cache()`, which memoises\n * per request:\n *\n * ```ts\n * ConfigManager.setQueryClientResolver(() => getQueryClient());\n * ```\n *\n * Registering a resolver supersedes any client previously passed to\n * `setQueryClient`; assigning a client afterwards supersedes the resolver.\n */\n export function setQueryClientResolver(resolve: () => QueryClient) {\n queryClientResolver = resolve;\n }\n\n /**\n * Set the private API host\n * @param host - The private API host URL (e.g., \"https://ecency.com\" or \"\" for relative URLs)\n */\n export function setPrivateApiHost(host: string) {\n CONFIG.privateApiHost = host;\n }\n\n /**\n * Set the first-party client identifier sent as the `X-Ecency-Client` header\n * on search/private API requests (e.g. \"web\" or \"mobile\"). Defaults to\n * \"ecency-sdk\". Used by the origin to tell Ecency's own apps apart from\n * third-party integrators.\n * @param clientId - Short client label\n */\n export function setClientId(clientId: string) {\n CONFIG.clientId = clientId;\n }\n\n /**\n * Set the observer used for bridge calls made without a logged-in user.\n * Defaults to \"ecency\"; a third-party integrator should point this at their\n * own moderation account.\n *\n * Must be a real account. An empty value is rejected rather than treated as\n * an opt-out: consumers resolve the observer with `||`, and `getDiscussion`\n * separately falls back to the post author, so \"\" would not disable mute\n * marking. It would silently observe as someone else while being cached under\n * \"\", leaving the request and its cache key describing different things.\n * @param observer - Hive account whose mute list applies to anonymous reads\n * @throws If given an empty or whitespace-only value\n */\n export function setDefaultObserver(observer: string) {\n if (typeof observer !== \"string\" || observer.trim() === \"\") {\n throw new Error(\n \"setDefaultObserver requires a non-empty Hive account. There is no empty-string opt-out; \" +\n \"observer resolution would fall back to the post author while caching under an empty key.\"\n );\n }\n\n CONFIG.defaultObserver = observer;\n }\n\n /**\n * Get a validated base URL for API requests\n * Returns a valid base URL that can be used with new URL(path, baseUrl)\n *\n * Priority:\n * 1. CONFIG.privateApiHost if set (dev/staging or explicit config)\n * 2. window.location.origin if in browser (production with relative URLs)\n * 3. 'https://ecency.com' as fallback for SSR (production default)\n *\n * @returns A valid base URL string\n * @throws Never throws - always returns a valid URL\n */\n export function getValidatedBaseUrl(): string {\n if (CONFIG.privateApiHost) {\n return CONFIG.privateApiHost;\n }\n\n if (typeof window !== 'undefined' && window.location?.origin) {\n return window.location.origin;\n }\n\n // Fallback for SSR when privateApiHost is empty (production case)\n return 'https://ecency.com';\n }\n\n /**\n * Set the polls API host\n * @param host - The polls API host URL (e.g., \"https://poll.ecency.com\")\n */\n export function setPollsApiHost(host: string) {\n CONFIG.pollsApiHost = host;\n }\n\n /**\n * Set the image host\n * @param host - The image host URL (e.g., \"https://i.ecency.com\")\n */\n export function setImageHost(host: string) {\n CONFIG.imageHost = host;\n }\n\n /**\n * Set Hive RPC nodes, replacing the default list.\n * Delegates to the unified hive-tx `setNodes` (single validated setter,\n * shared with the lean `@ecency/sdk/hive` entry) so node configuration is\n * defined in exactly one place.\n * @param nodes - Array of Hive RPC node URLs\n */\n export function setHiveNodes(nodes: string[]) {\n setHiveTxNodes(nodes);\n }\n\n /**\n * Set the REST-API node list, replacing the default `restNodes`. Lets an app\n * add/remove REST hosts at runtime (e.g. drop an own node being decommissioned,\n * or widen the public pool) without forking + republishing the SDK. Delegates to\n * the unified hive-tx `setRestNodes` (validated, shared with `@ecency/sdk/hive`).\n * @param nodes - Array of REST-capable node URLs (without a trailing slash)\n */\n export function setRestNodes(nodes: string[]) {\n setHiveTxRestNodes(nodes);\n }\n\n /**\n * Merge per-API REST node overrides. For each API a non-empty valid list pins it\n * to those hosts (so `callREST` never wastes its retry budget on a node that\n * 404/503s the API); an empty list removes the pin (falls back to `restNodes`).\n * Other APIs' pins (e.g. the built-in `hivesense`) are preserved. Delegates to the\n * unified hive-tx `setRestNodesByApi`.\n * @param map - Partial map of REST API name → capable node URLs\n */\n export function setRestNodesByApi(map: Partial>) {\n setHiveTxRestNodesByApi(map);\n }\n\n /**\n * Set the User-Agent sent on server-side (Node) requests to Hive nodes.\n * Lets an app label its own SSR/server traffic (otherwise Node's fetch sends a\n * bare `node` UA). No effect in browsers (User-Agent is a forbidden header) or\n * React Native (keeps its native UA). Delegates to the unified hive-tx setter.\n * @param userAgent - The User-Agent string (e.g. \"ecency-web-ssr (+https://ecency.com)\")\n */\n export function setUserAgent(userAgent: string) {\n setHiveTxUserAgent(userAgent);\n }\n\n /**\n * Tune read-call tail-latency resilience: adaptive per-attempt timeouts\n * (default on) and hedged requests (default OFF — a duplicate request races\n * the next healthy node when the primary stalls, bounded by a token bucket so\n * only the slow tail hedges and pool-wide slowness self-disables it). Partial:\n * only the fields provided are changed; invalid values are ignored\n * field-by-field. Delegates to the unified hive-tx `setResilience`.\n * @param opts - e.g. `{ hedge: true }` to opt into hedged reads\n */\n export function setResilience(opts: Partial) {\n setHiveTxResilience(opts);\n }\n\n /**\n * Static analysis: Check for known ReDoS-vulnerable patterns\n * @param pattern - Raw regex pattern string\n * @returns Object with risk level and reason\n */\n function analyzeRedosRisk(pattern: string): { safe: boolean; reason?: string } {\n // Check 1: Nested quantifiers (e.g., (a+)+, (a*)+, (a{1,})+)\n if (/(\\([^)]*[*+{][^)]*\\))[*+{]/.test(pattern)) {\n return { safe: false, reason: \"nested quantifiers detected\" };\n }\n\n // Check 2: Alternation with overlapping terms (e.g., (a|a)+, (ab|a)+)\n if (/\\([^|)]*\\|[^)]*\\)[*+{]/.test(pattern)) {\n return { safe: false, reason: \"alternation with quantifier (potential overlap)\" };\n }\n\n // Check 3: Catastrophic backtracking patterns (e.g., (a*)*b, (a+)+b)\n if (/\\([^)]*[*+][^)]*\\)[*+]/.test(pattern)) {\n return { safe: false, reason: \"repeated quantifiers (catastrophic backtracking risk)\" };\n }\n\n // Check 4: Greedy quantifiers followed by optional patterns (e.g., .*.*x, .+.+x)\n if (/\\.\\*\\.\\*/.test(pattern) || /\\.\\+\\.\\+/.test(pattern)) {\n return { safe: false, reason: \"multiple greedy quantifiers on wildcards\" };\n }\n\n // Check 5: Unbounded ranges with wildcards (e.g., .{1,999999})\n const unboundedRange = /\\.?\\{(\\d+),(\\d+)\\}/g;\n let match;\n while ((match = unboundedRange.exec(pattern)) !== null) {\n const [, min, max] = match;\n const range = parseInt(max, 10) - parseInt(min, 10);\n if (range > 1000) {\n return { safe: false, reason: `excessive range: {${min},${max}}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Runtime test: Execute regex against adversarial inputs with timeout\n * @param regex - Compiled regex\n * @returns Object indicating if regex passed runtime test\n */\n function testRegexPerformance(regex: RegExp): { safe: boolean; reason?: string } {\n // Test inputs designed to trigger ReDoS in vulnerable patterns\n const adversarialInputs = [\n // Nested quantifier attack\n \"a\".repeat(50) + \"x\",\n // Alternation attack\n \"ab\".repeat(50) + \"x\",\n // Wildcard attack\n \"x\".repeat(100),\n // Mixed attack\n \"aaa\".repeat(30) + \"bbb\".repeat(30) + \"x\",\n ];\n\n const maxExecutionTime = 5; // 5ms hard limit per test\n\n for (const input of adversarialInputs) {\n const start = Date.now();\n try {\n regex.test(input);\n const duration = Date.now() - start;\n\n if (duration > maxExecutionTime) {\n return {\n safe: false,\n reason: `runtime test exceeded ${maxExecutionTime}ms (took ${duration}ms on input length ${input.length})`\n };\n }\n } catch (err) {\n return { safe: false, reason: `runtime test threw error: ${err}` };\n }\n }\n\n return { safe: true };\n }\n\n /**\n * Safely compile a regex pattern with defense-in-depth validation\n * @param pattern - Raw regex pattern string\n * @param maxLength - Maximum allowed pattern length (default 200)\n * @returns Compiled RegExp or null if invalid/unsafe\n */\n function safeCompileRegex(pattern: string, maxLength = 200): RegExp | null {\n // Use the module-level isDevelopment constant\n\n try {\n // Layer 1: Basic validation\n if (!pattern) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: empty pattern`);\n }\n return null;\n }\n\n if (pattern.length > maxLength) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: length ${pattern.length} exceeds max ${maxLength} - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 2: Static ReDoS analysis\n const staticAnalysis = analyzeRedosRisk(pattern);\n if (!staticAnalysis.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${staticAnalysis.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n // Layer 3: Compilation attempt\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (compileErr) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${pattern.substring(0, 50)}...`, compileErr);\n }\n return null;\n }\n\n // Layer 4: Runtime performance testing\n const runtimeTest = testRegexPerformance(regex);\n if (!runtimeTest.safe) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${runtimeTest.reason}) - pattern: ${pattern.substring(0, 50)}...`);\n }\n return null;\n }\n\n return regex;\n } catch (err) {\n if (isDevelopment) {\n console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${pattern.substring(0, 50)}...`, err);\n }\n return null;\n }\n }\n\n /**\n * Set DMCA filtering lists\n * @param lists - DMCA lists object containing accounts/tags/posts arrays\n */\n export function setDmcaLists(\n lists: DmcaListsInput = {}\n ) {\n const coerceList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n\n // Ensure we have a valid object to work with\n const input = lists || {};\n\n const resolved = {\n accounts: coerceList(input.accounts),\n tags: coerceList(input.tags),\n patterns: coerceList(input.posts),\n };\n\n CONFIG.dmcaAccounts = resolved.accounts;\n CONFIG.dmcaTags = resolved.tags;\n CONFIG.dmcaPatterns = resolved.patterns;\n\n // Pre-compile tag regex patterns (tags can be regex)\n CONFIG.dmcaTagRegexes = resolved.tags\n .map((pattern) => safeCompileRegex(pattern))\n .filter((r): r is RegExp => r !== null);\n\n // Post patterns are plain strings for exact matching, not regex\n // No compilation needed - they will be used with simple string comparison\n CONFIG.dmcaPatternRegexes = [];\n\n const rejectedTagCount = resolved.tags.length - CONFIG.dmcaTagRegexes.length;\n\n // Only log once to avoid noise during builds/hot reloads\n // Only show in development mode to avoid cluttering production console\n // Use the module-level isDevelopment constant\n\n if (!CONFIG._dmcaInitialized && isDevelopment) {\n console.log(`[SDK] DMCA configuration loaded:`);\n console.log(` - Accounts: ${resolved.accounts.length}`);\n console.log(` - Tag patterns: ${CONFIG.dmcaTagRegexes.length}/${resolved.tags.length} compiled (${rejectedTagCount} rejected)`);\n console.log(` - Post patterns: ${resolved.patterns.length} (using exact string matching)`);\n\n if (rejectedTagCount > 0) {\n console.warn(`[SDK] ${rejectedTagCount} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`);\n }\n }\n\n CONFIG._dmcaInitialized = true;\n }\n}\n","import {\n InfiniteData,\n QueryClient,\n QueryKey,\n useInfiniteQuery,\n UseInfiniteQueryOptions,\n useQuery,\n UseQueryOptions,\n} from \"@tanstack/react-query\";\nimport { CONFIG } from \"./config\";\n\n/**\n * Builds a client with the SDK's defaults. It is only a factory — request\n * scoping is the host's job, via `ConfigManager.setQueryClientResolver`, since\n * only the host knows where one request ends and the next begins.\n */\nexport function makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // With SSR, we usually want to set some default staleTime\n // above 0 to avoid refetching immediately on the client\n // staleTime: 60 * 1000,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n },\n },\n });\n}\nexport const getQueryClient = () => CONFIG.queryClient;\n\nexport namespace EcencyQueriesManager {\n export function getQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData(queryKey);\n }\n\n export function getInfiniteQueryData(queryKey: QueryKey) {\n const queryClient = getQueryClient();\n return queryClient.getQueryData>(queryKey);\n }\n\n export async function prefetchQuery(options: UseQueryOptions) {\n const queryClient = getQueryClient();\n await queryClient.prefetchQuery(options);\n return getQueryData(options.queryKey);\n }\n\n export async function prefetchInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n const queryClient = getQueryClient();\n await queryClient.prefetchInfiniteQuery(options);\n return getInfiniteQueryData(options.queryKey);\n }\n\n export function generateClientServerQuery(options: UseQueryOptions) {\n return {\n prefetch: () => prefetchQuery(options),\n getData: () => getQueryData(options.queryKey),\n useClientQuery: () => useQuery(options),\n fetchAndGet: () => getQueryClient().fetchQuery(options),\n };\n }\n\n export function generateClientServerInfiniteQuery(\n options: UseInfiniteQueryOptions<\n T,\n Error,\n InfiniteData,\n QueryKey,\n P\n >\n ) {\n return {\n prefetch: () => prefetchInfiniteQuery(options),\n getData: () => getInfiniteQueryData(options.queryKey),\n useClientQuery: () => useInfiniteQuery(options),\n fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options),\n };\n }\n}\n","export function encodeObj(o: any): string {\n return btoa(JSON.stringify(o));\n}\n\nexport function decodeObj(o: any): any {\n let dataToParse = atob(o);\n if (dataToParse[0] !== \"{\") {\n return undefined;\n }\n return JSON.parse(dataToParse);\n}\n","import type { SMTAsset } from \"@/modules/core/hive-tx\";\n\nexport enum Symbol {\n HIVE = \"HIVE\",\n HBD = \"HBD\",\n VESTS = \"VESTS\",\n}\n\nexport enum NaiMap {\n \"@@000000021\" = \"HIVE\",\n \"@@000000013\" = \"HBD\",\n \"@@000000037\" = \"VESTS\",\n}\n\nexport interface Asset {\n amount: number;\n symbol: Symbol;\n}\n\nexport function parseAsset(sval: string | SMTAsset): Asset {\n if (typeof sval === \"string\") {\n const sp = sval.split(\" \");\n return {\n amount: parseFloat(sp[0]),\n // @ts-ignore\n symbol: Symbol[sp[1]],\n };\n } else {\n return {\n amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),\n // @ts-ignore\n symbol: NaiMap[sval.nai],\n };\n }\n}\n","let cachedFetch: typeof globalThis.fetch | undefined;\n\nexport function getBoundFetch() {\n if (!cachedFetch) {\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"[Ecency][SDK] - global fetch is not available\");\n }\n\n cachedFetch = globalThis.fetch.bind(globalThis);\n }\n\n return cachedFetch;\n}\n","export function isCommunity(value: unknown) {\n return typeof value === \"string\" ? /^hive-\\d+$/.test(value) : false;\n}\n","import { WrappedResponse } from \"../types/pagination\";\n\n/**\n * Type guard to check if response is wrapped with pagination metadata\n */\nexport function isWrappedResponse(response: any): response is WrappedResponse {\n return (\n response &&\n typeof response === \"object\" &&\n \"data\" in response &&\n \"pagination\" in response &&\n Array.isArray(response.data)\n );\n}\n\n/**\n * Normalize response to wrapped format for backwards compatibility\n * If the backend returns old format (array), convert it to wrapped format\n */\nexport function normalizeToWrappedResponse(\n response: T[] | WrappedResponse,\n limit: number\n): WrappedResponse {\n if (isWrappedResponse(response)) {\n return response;\n }\n\n // Old format - just an array\n // Since we don't have pagination metadata, assume no more pages\n return {\n data: Array.isArray(response) ? response : [],\n pagination: {\n total: Array.isArray(response) ? response.length : 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n}\n","export function vestsToHp(vests: number, hivePerMVests: number): number {\n return (vests / 1e6) * hivePerMVests;\n}\n","export function isEmptyDate(s: string | undefined): boolean {\n if (s === undefined) {\n return true;\n }\n\n return parseInt(s.split(\"-\")[0], 10) < 1980;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { DynamicProps } from \"../types\";\nimport { parseAsset } from \"../utils\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// This query powers wallet/HP/reward math that should stay close to chain state.\n// Keep a short refresh cadence despite the 5 RPC calls.\nconst DYNAMIC_PROPS_REFRESH_MS = 60 * 1000;\n\nexport function getDynamicPropsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.core.dynamicProps(),\n refetchInterval: DYNAMIC_PROPS_REFRESH_MS,\n staleTime: DYNAMIC_PROPS_REFRESH_MS,\n queryFn: async ({ signal }): Promise => {\n // Get raw blockchain data — all five calls are independent, run in parallel.\n // Hardfork properties is wrapped with catch since not all nodes support it.\n const [rawGlobalDynamic, rawFeedHistory, rawChainProps, rawRewardFund, rawHardforkProps] = await Promise.all([\n callRPC(\"condenser_api.get_dynamic_global_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_feed_history\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_chain_properties\", [], undefined, undefined, signal),\n callRPC(\"condenser_api.get_reward_fund\", [\"post\"], undefined, undefined, signal),\n callRPC(\"database_api.get_hardfork_properties\", {}, undefined, undefined, signal)\n .catch(() => ({ current_hardfork_version: \"1.28.0\", last_hardfork: 28 })),\n ]) as [any, any, any, any, any];\n\n // Calculate derived values for backward compatibility\n // parseAsset handles both string format (\"200905388484 HIVE\") and NAI format ({ amount, nai, precision })\n const totalVestingSharesAmount = parseAsset(rawGlobalDynamic.total_vesting_shares).amount;\n const totalVestingFundAmount = parseAsset(rawGlobalDynamic.total_vesting_fund_hive).amount;\n\n // Guard against division by zero/NaN/Infinity\n let hivePerMVests = 0;\n if (\n Number.isFinite(totalVestingSharesAmount) &&\n totalVestingSharesAmount !== 0 &&\n Number.isFinite(totalVestingFundAmount)\n ) {\n hivePerMVests = (totalVestingFundAmount / totalVestingSharesAmount) * 1e6;\n }\n const base = parseAsset(rawFeedHistory.current_median_history.base).amount;\n const quote = parseAsset(rawFeedHistory.current_median_history.quote).amount;\n const fundRecentClaims = parseFloat(rawRewardFund.recent_claims);\n const fundRewardBalance = parseAsset(rawRewardFund.reward_balance).amount;\n const votePowerReserveRate = Number(rawGlobalDynamic.vote_power_reserve_rate ?? 0);\n const authorRewardCurve = rawRewardFund.author_reward_curve ?? \"linear\";\n const contentConstant = Number(rawRewardFund.content_constant ?? 0);\n const currentHardforkVersion = String(rawHardforkProps.current_hardfork_version ?? \"0.0.0\");\n const lastHardfork = Number(rawHardforkProps.last_hardfork ?? 0);\n const hbdPrintRate = rawGlobalDynamic.hbd_print_rate;\n const hbdInterestRate = rawGlobalDynamic.hbd_interest_rate;\n const headBlock = rawGlobalDynamic.head_block_number;\n const totalVestingFund = totalVestingFundAmount;\n const totalVestingShares = totalVestingSharesAmount;\n const virtualSupply = parseAsset(rawGlobalDynamic.virtual_supply).amount;\n const vestingRewardPercent = rawGlobalDynamic.vesting_reward_percent || 0;\n const accountCreationFee = rawChainProps.account_creation_fee;\n\n return {\n // Backward compatible transformed fields (camelCase, parsed)\n hivePerMVests,\n base,\n quote,\n fundRecentClaims,\n fundRewardBalance,\n votePowerReserveRate,\n authorRewardCurve,\n contentConstant,\n currentHardforkVersion,\n lastHardfork,\n hbdPrintRate,\n hbdInterestRate,\n headBlock,\n totalVestingFund,\n totalVestingShares,\n virtualSupply,\n vestingRewardPercent,\n accountCreationFee,\n\n // Raw blockchain data (snake_case, unparsed) for direct use\n // Includes ALL fields from the blockchain responses\n raw: {\n globalDynamic: rawGlobalDynamic,\n feedHistory: rawFeedHistory,\n chainProps: rawChainProps,\n rewardFund: rawRewardFund,\n hardforkProps: rawHardforkProps,\n },\n } as DynamicProps;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface RewardFund {\n id: number;\n name: string;\n reward_balance: string;\n recent_claims: string;\n last_update: string;\n content_constant: string;\n percent_curation_rewards: number;\n percent_content_rewards: number;\n author_reward_curve: string;\n curation_reward_curve: string;\n}\n\n/**\n * Get reward fund information from the blockchain\n * @param fundName - Name of the reward fund (default: 'post')\n */\nexport function getRewardFundQueryOptions(fundName = \"post\") {\n return queryOptions({\n queryKey: QueryKeys.core.rewardFund(fundName),\n queryFn: () =>\n callRPC(\"condenser_api.get_reward_fund\", [\n fundName,\n ]) as Promise,\n });\n}\n","/**\n * Centralized query key definitions for all SDK queries.\n *\n * These key builders are the single source of truth for React Query cache keys.\n * Both SDK query options and web app consumers should reference these\n * instead of using inline string arrays.\n *\n * @example\n * ```typescript\n * import { QueryKeys } from \"@ecency/sdk\";\n *\n * // In query options\n * queryKey: QueryKeys.posts.entry(`/@${author}/${permlink}`)\n *\n * // In cache invalidation\n * queryClient.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) })\n * ```\n */\n/** Strip trailing undefined values so the key works as a prefix for partialMatchKey */\nfunction key(...parts: unknown[]): unknown[] {\n let end = parts.length;\n while (end > 0 && parts[end - 1] === undefined) {\n end--;\n }\n return parts.slice(0, end);\n}\n\nexport const QueryKeys = {\n // ===========================================================================\n // Posts\n // ===========================================================================\n posts: {\n entry: (entryPath: string) => [\"posts\", \"entry\", entryPath],\n postHeader: (author: string, permlink?: string) =>\n [\"posts\", \"post-header\", author, permlink],\n content: (author: string, permlink: string) =>\n [\"posts\", \"content\", author, permlink],\n contentReplies: (author: string, permlink: string) =>\n [\"posts\", \"content-replies\", author, permlink],\n accountPosts: (\n username: string,\n filter: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"account-posts\", username, filter, limit, observer],\n accountPostsPage: (\n username: string,\n filter: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n observer: string\n ) =>\n [\n \"posts\",\n \"account-posts-page\",\n username,\n filter,\n startAuthor,\n startPermlink,\n limit,\n observer,\n ],\n userPostVote: (username: string, author: string, permlink: string) =>\n [\"posts\", \"user-vote\", username, author, permlink],\n reblogs: (username: string, limit: number) =>\n [\"posts\", \"reblogs\", username, limit],\n entryActiveVotes: (author?: string, permlink?: string) =>\n [\"posts\", \"entry-active-votes\", author, permlink],\n rebloggedBy: (author: string, permlink: string) =>\n [\"posts\", \"reblogged-by\", author, permlink],\n tips: (author: string, permlink: string) =>\n [\"posts\", \"tips\", author, permlink],\n normalize: (author: string, permlink: string) =>\n [\"posts\", \"normalize\", author, permlink],\n drafts: (activeUsername?: string) =>\n [\"posts\", \"drafts\", activeUsername],\n draftsInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"drafts\", \"infinite\", activeUsername, limit),\n schedules: (activeUsername?: string) =>\n [\"posts\", \"schedules\", activeUsername],\n schedulesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"posts\", \"schedules\", \"infinite\", activeUsername, limit),\n fragments: (username?: string) =>\n [\"posts\", \"fragments\", username],\n fragmentsInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"fragments\", \"infinite\", username, limit),\n images: (username?: string) => [\"posts\", \"images\", username],\n galleryImages: (activeUsername?: string) =>\n [\"posts\", \"gallery-images\", activeUsername],\n imagesInfinite: (username?: string, limit?: number) =>\n key(\"posts\", \"images\", \"infinite\", username, limit),\n promoted: (type: string) => [\"posts\", \"promoted\", type],\n _promotedPrefix: [\"posts\", \"promoted\"],\n accountPostsBlogPrefix: (username: string) =>\n [\"posts\", \"account-posts\", username, \"blog\"] as const,\n postsRanked: (\n sort: string,\n tag: string,\n limit: number,\n observer: string\n ) => [\"posts\", \"posts-ranked\", sort, tag, limit, observer],\n postsRankedPage: (\n sort: string,\n startAuthor: string,\n startPermlink: string,\n limit: number,\n tag: string,\n observer: string\n ) =>\n [\n \"posts\",\n \"posts-ranked-page\",\n sort,\n startAuthor,\n startPermlink,\n limit,\n tag,\n observer,\n ],\n discussions: (\n author: string,\n permlink: string,\n order: string,\n observer: string\n ) => [\"posts\", \"discussions\", author, permlink, order, observer],\n discussion: (author: string, permlink: string, observer: string) =>\n [\"posts\", \"discussion\", author, permlink, observer],\n deletedEntry: (entryPath: string) =>\n [\"posts\", \"deleted-entry\", entryPath],\n commentHistory: (\n author: string,\n permlink: string,\n onlyMeta: boolean\n ) => [\"posts\", \"comment-history\", author, permlink, onlyMeta],\n trendingTags: () => [\"posts\", \"trending-tags\"],\n trendingTagsWithStats: (limit: number) =>\n [\"posts\", \"trending-tags\", \"stats\", limit],\n wavesFeed: (\n params: {\n containers?: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"feed\",\n params.tag ?? \"\",\n params.following ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n shortsFeed: (\n params: {\n containers?: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit?: number;\n } = {}\n ) => [\n \"posts\",\n \"waves\",\n \"shorts\",\n params.tag ?? \"\",\n params.author ?? \"\",\n params.observer ?? \"\",\n params.limit ?? 0,\n [...(params.containers ?? [])].sort().join(\",\")\n ],\n wavesByHost: (host: string) =>\n [\"posts\", \"waves\", \"by-host\", host],\n wavesByTag: (host: string, tag: string) =>\n [\"posts\", \"waves\", \"by-tag\", host, tag],\n wavesFollowing: (host: string, username: string) =>\n [\"posts\", \"waves\", \"following\", host, username],\n wavesTrendingTags: (host: string, hours: number) =>\n [\"posts\", \"waves\", \"trending-tags\", host, hours],\n wavesByAccount: (host: string, username: string) =>\n [\"posts\", \"waves\", \"by-account\", host, username],\n wavesTrendingAuthors: (host: string) =>\n [\"posts\", \"waves\", \"trending-authors\", host],\n _prefix: [\"posts\"],\n },\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n accounts: {\n full: (username?: string) => [\"get-account-full\", username],\n list: (...usernames: string[]) =>\n [\"accounts\", \"list\", ...usernames],\n friends: (\n following: string,\n mode: string,\n followType: string,\n limit: number\n ) => [\"accounts\", \"friends\", following, mode, followType, limit],\n searchFriends: (username: string, mode: string, query: string) =>\n [\"accounts\", \"friends\", \"search\", username, mode, query],\n subscriptions: (username: string) =>\n [\"accounts\", \"subscriptions\", username],\n followCount: (username: string) =>\n [\"accounts\", \"follow-count\", username],\n recoveries: (username: string) =>\n [\"accounts\", \"recoveries\", username],\n pendingRecovery: (username: string) =>\n [\"accounts\", \"recoveries\", username, \"pending-request\"],\n checkWalletPending: (username: string, code: string | null) =>\n [\"accounts\", \"check-wallet-pending\", username, code],\n mutedUsers: (username: string) =>\n [\"accounts\", \"muted-users\", username],\n following: (\n follower: string,\n startFollowing: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"following\",\n follower,\n startFollowing,\n followType,\n limit,\n ],\n followers: (\n following: string,\n startFollower: string,\n followType: string,\n limit: number\n ) =>\n [\n \"accounts\",\n \"followers\",\n following,\n startFollower,\n followType,\n limit,\n ],\n search: (query: string, excludeList?: string[]) =>\n [\"accounts\", \"search\", query, excludeList],\n profiles: (accounts: string[], observer: string) =>\n [\"accounts\", \"profiles\", accounts, observer],\n lookup: (query: string, limit: number) =>\n [\"accounts\", \"lookup\", query, limit],\n transactions: (username: string, group: string, limit: number) =>\n [\"accounts\", \"transactions\", username, group, limit],\n favorites: (activeUsername?: string) =>\n [\"accounts\", \"favorites\", activeUsername],\n favoritesInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"favorites\", \"infinite\", activeUsername, limit),\n checkFavorite: (activeUsername: string, targetUsername: string) =>\n [\n \"accounts\",\n \"favorites\",\n \"check\",\n activeUsername,\n targetUsername,\n ],\n relations: (reference: string | undefined, target: string | undefined) =>\n [\"accounts\", \"relations\", reference, target],\n bots: () => [\"accounts\", \"bots\"],\n voteHistory: (username: string, limit: number) =>\n [\"accounts\", \"vote-history\", username, limit],\n reputations: (query: string, limit: number) =>\n [\"accounts\", \"reputations\", query, limit],\n bookmarks: (activeUsername?: string) =>\n [\"accounts\", \"bookmarks\", activeUsername],\n bookmarksInfinite: (activeUsername?: string, limit?: number) =>\n key(\"accounts\", \"bookmarks\", \"infinite\", activeUsername, limit),\n referrals: (username: string) =>\n [\"accounts\", \"referrals\", username],\n referralsStats: (username: string) =>\n [\"accounts\", \"referrals-stats\", username],\n proMembers: () => [\"accounts\", \"pro-members\"],\n _prefix: [\"accounts\"],\n },\n\n // ===========================================================================\n // Notifications\n // ===========================================================================\n notifications: {\n announcements: () => [\"notifications\", \"announcements\"],\n spotlights: () => [\"notifications\", \"spotlights\"],\n list: (activeUsername?: string, filter?: string) =>\n [\"notifications\", activeUsername, filter],\n unreadCount: (activeUsername?: string) =>\n [\"notifications\", \"unread\", activeUsername],\n settings: (activeUsername?: string) =>\n [\"notifications\", \"settings\", activeUsername],\n _prefix: [\"notifications\"],\n },\n\n // ===========================================================================\n // Core\n // ===========================================================================\n core: {\n rewardFund: (fundName: string) =>\n [\"core\", \"reward-fund\", fundName],\n dynamicProps: () => [\"core\", \"dynamic-props\"],\n chainProperties: () => [\"core\", \"chain-properties\"],\n _prefix: [\"core\"],\n },\n\n // ===========================================================================\n // Communities\n // ===========================================================================\n communities: {\n single: (name?: string, observer?: string) =>\n [\"community\", \"single\", name, observer],\n /** Prefix key for matching all observer variants of a community */\n singlePrefix: (name: string) =>\n [\"community\", \"single\", name] as const,\n context: (username: string, communityName: string) =>\n [\"community\", \"context\", username, communityName],\n rewarded: () => [\"communities\", \"rewarded\"],\n list: (sort: string, query: string, limit: number) =>\n [\"communities\", \"list\", sort, query, limit],\n subscribers: (communityName: string) =>\n [\"communities\", \"subscribers\", communityName],\n subscribersInfinite: (communityName: string) =>\n [\"communities\", \"subscribers\", \"infinite\", communityName],\n accountNotifications: (account: string, limit: number) =>\n [\"communities\", \"account-notifications\", account, limit],\n },\n\n // ===========================================================================\n // Proposals\n // ===========================================================================\n proposals: {\n list: () => [\"proposals\", \"list\"],\n proposal: (id: number) => [\"proposals\", \"proposal\", id],\n votes: (proposalId: number, voter: string, limit: number) =>\n [\"proposals\", \"votes\", proposalId, voter, limit],\n votesPrefix: (proposalId: number) =>\n [\"proposals\", \"votes\", proposalId] as const,\n votesByUser: (voter: string) =>\n [\"proposals\", \"votes\", \"by-user\", voter],\n },\n\n // ===========================================================================\n // Search\n // ===========================================================================\n search: {\n topics: (q: string, limit: number) => [\"search\", \"topics\", q, limit],\n path: (q: string) => [\"search\", \"path\", q],\n account: (q: string, limit: number) =>\n [\"search\", \"account\", q, limit],\n results: (\n q: string,\n sort: string,\n hideLow: boolean | string,\n since?: string,\n scrollId?: string,\n votes?: number\n ) => {\n const normalizedHideLow = typeof hideLow === \"string\" ? hideLow === \"1\" || hideLow === \"true\" : hideLow;\n return [\"search\", q, sort, normalizedHideLow, since, scrollId, votes] as const;\n },\n controversialRising: (what: string, tag: string) =>\n [\"search\", \"controversial-rising\", what, tag],\n similarEntries: (author: string, permlink: string, content?: string) =>\n content\n ? [\"search\", \"similar-entries\", author, permlink, content]\n : [\"search\", \"similar-entries\", author, permlink],\n api: (\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n ) => key(\"search\", \"api\", q, sort, hideLow, since, votes, includeNsfw),\n },\n\n // ===========================================================================\n // Witnesses\n // ===========================================================================\n witnesses: {\n list: (limit: number) => [\"witnesses\", \"list\", limit],\n votes: (username: string | undefined) => [\"witnesses\", \"votes\", username],\n proxy: () => [\"witnesses\", \"proxy\"],\n voters: (\n witness: string,\n page: number,\n pageSize: number,\n sort: string,\n direction: string\n ) => [\"witnesses\", \"voters\", witness, page, pageSize, sort, direction],\n voterCount: (witness: string) =>\n [\"witnesses\", \"voter-count\", witness],\n },\n\n // ===========================================================================\n // Wallet\n // ===========================================================================\n wallet: {\n outgoingRcDelegations: (username: string, limit: number) =>\n [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n vestingDelegations: (username: string, limit: number) =>\n [\"wallet\", \"vesting-delegations\", username, limit],\n withdrawRoutes: (account: string) =>\n [\"wallet\", \"withdraw-routes\", account],\n incomingRc: (username: string) =>\n [\"wallet\", \"incoming-rc\", username],\n conversionRequests: (account: string) =>\n [\"wallet\", \"conversion-requests\", account],\n receivedVestingShares: (username: string) =>\n [\"wallet\", \"received-vesting-shares\", username],\n savingsWithdraw: (account: string) =>\n [\"wallet\", \"savings-withdraw\", account],\n openOrders: (user: string) =>\n [\"wallet\", \"open-orders\", user],\n collateralizedConversionRequests: (account: string) =>\n [\"wallet\", \"collateralized-conversion-requests\", account],\n recurrentTransfers: (username: string) =>\n [\"wallet\", \"recurrent-transfers\", username],\n balanceHistory: (username: string, coinType: string, pageSize: number) =>\n [\"wallet\", \"balance-history\", username, coinType, pageSize],\n aggregatedHistory: (\n username: string,\n coinType: string,\n granularity?: \"yearly\" | \"monthly\" | \"daily\"\n ) =>\n granularity === undefined\n ? [\"wallet\", \"aggregated-history\", username, coinType]\n : [\"wallet\", \"aggregated-history\", username, coinType, granularity],\n portfolio: (\n username: string,\n onlyEnabled: string,\n currency: string\n ) =>\n [\"wallet\", \"portfolio\", \"v2\", username, onlyEnabled, currency],\n },\n\n // ===========================================================================\n // Assets\n // ===========================================================================\n assets: {\n hiveGeneralInfo: (username: string) =>\n [\"assets\", \"hive\", \"general-info\", username],\n hiveTransactions: (username: string, limit: number, filterKey: string) =>\n [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n hiveWithdrawalRoutes: (username: string) =>\n [\"assets\", \"hive\", \"withdrawal-routes\", username],\n hiveMetrics: (bucketSeconds: number) =>\n [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n hbdGeneralInfo: (username: string) =>\n [\"assets\", \"hbd\", \"general-info\", username],\n hbdTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) => [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n hivePowerGeneralInfo: (username: string) =>\n [\"assets\", \"hive-power\", \"general-info\", username],\n hivePowerDelegates: (username: string) =>\n [\"assets\", \"hive-power\", \"delegates\", username],\n hivePowerDelegatings: (username: string) =>\n [\"assets\", \"hive-power\", \"delegatings\", username],\n hivePowerTransactions: (\n username: string,\n limit: number,\n filterKey: string\n ) =>\n [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n pointsGeneralInfo: (username: string) =>\n [\"assets\", \"points\", \"general-info\", username],\n pointsTransactions: (username: string, type: string) =>\n [\"assets\", \"points\", \"transactions\", username, type],\n ecencyAssetInfo: (username: string, asset: string, currency: string) =>\n [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n },\n\n // ===========================================================================\n // Market\n // ===========================================================================\n market: {\n statistics: () => [\"market\", \"statistics\"],\n orderBook: (limit: number) => [\"market\", \"order-book\", limit],\n history: (seconds: number, startDate: number, endDate: number) =>\n [\"market\", \"history\", seconds, startDate, endDate],\n feedHistory: () => [\"market\", \"feed-history\"],\n hiveHbdStats: () => [\"market\", \"hive-hbd-stats\"],\n data: (\n coin: string,\n vsCurrency: string,\n fromTs: number,\n toTs: number\n ) => [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n tradeHistory: (limit: number, start: number, end: number) =>\n [\"market\", \"trade-history\", limit, start, end],\n currentMedianHistoryPrice: () =>\n [\"market\", \"current-median-history-price\"],\n },\n\n // ===========================================================================\n // Analytics\n // ===========================================================================\n analytics: {\n discoverCuration: (duration: string) =>\n [\"analytics\", \"discover-curation\", duration],\n pageStats: (\n url: string,\n dimensions: string,\n metrics: string,\n dateRange: string\n ) =>\n [\"analytics\", \"page-stats\", url, dimensions, metrics, dateRange],\n discoverLeaderboard: (duration: string) =>\n [\"analytics\", \"discover-leaderboard\", duration],\n },\n\n // ===========================================================================\n // Promotions\n // ===========================================================================\n promotions: {\n promotePrice: () => [\"promotions\", \"promote-price\"],\n boostPlusPrices: () => [\"promotions\", \"boost-plus-prices\"],\n boostPlusAccounts: (account: string) =>\n [\"promotions\", \"boost-plus-accounts\", account],\n },\n\n // ===========================================================================\n // Resource Credits\n // ===========================================================================\n resourceCredits: {\n account: (username: string) =>\n [\"resource-credits\", \"account\", username],\n stats: () => [\"resource-credits\", \"stats\"],\n resourceParams: () => [\"resource-credits\", \"resource-params\"],\n },\n\n // ===========================================================================\n // Points\n // ===========================================================================\n points: {\n points: (username: string, filter: number) =>\n [\"points\", username, filter],\n _prefix: (username: string) => [\"points\", username],\n },\n\n // ===========================================================================\n // Polls\n // ===========================================================================\n polls: {\n details: (author: string, permlink: string) =>\n [\"polls\", \"details\", author, permlink],\n vote: (author?: string, permlink?: string) =>\n author && permlink\n ? [\"polls\", \"vote\", author, permlink]\n : [\"polls\", \"vote\"],\n _prefix: [\"polls\"],\n },\n\n // ===========================================================================\n // Operations\n // ===========================================================================\n operations: {\n chainProperties: () => [\"operations\", \"chain-properties\"],\n },\n\n // ===========================================================================\n // Games\n // ===========================================================================\n games: {\n statusCheck: (gameType: string, username: string) =>\n [\"games\", \"status-check\", gameType, username],\n },\n\n quests: {\n status: (username: string | undefined) => [\"quests\", \"status\", username],\n },\n\n // ===========================================================================\n // Support Ecency\n // ===========================================================================\n support: {\n settings: (username: string | undefined) => [\"support\", \"settings\", username],\n _prefix: [\"support\"],\n },\n\n // ===========================================================================\n // Bad Actors\n // ===========================================================================\n badActors: {\n list: () => [\"bad-actors\", \"list\"],\n _prefix: [\"bad-actors\"],\n },\n\n // ===========================================================================\n // AI\n // ===========================================================================\n ai: {\n prices: () => [\"ai\", \"prices\"] as const,\n assistPrices: (username?: string) => [\"ai\", \"assist-prices\", username] as const,\n transcribePrice: (username?: string) => [\"ai\", \"transcribe-price\", username] as const,\n _prefix: [\"ai\"],\n },\n} as const;\n","/**\n * UTF-8 byte length of a string.\n *\n * `TextEncoder` is missing on some runtimes the SDK ships to (React Native /\n * Hermes), and `String.length` is NOT a substitute: it counts UTF-16 code\n * units, so anything non-ASCII is undercounted. Where that number feeds an RC\n * estimate, undercounting means telling someone a post is affordable when the\n * chain will reject it.\n */\nexport function utf8ByteLength(value: string): number {\n if (typeof TextEncoder !== \"undefined\") {\n return new TextEncoder().encode(value).length;\n }\n\n let bytes = 0;\n for (let i = 0; i < value.length; i++) {\n const c = value.charCodeAt(i);\n if (c < 0x80) {\n bytes += 1;\n } else if (c < 0x800) {\n bytes += 2;\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < value.length) {\n // surrogate pair encodes as four bytes\n i++;\n bytes += 4;\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n\n/** Byte length of Hive's unsigned LEB128 varint for `value`. */\nexport function varintByteLength(value: number): number {\n let count = 0;\n let remaining = value;\n do {\n count++;\n remaining >>>= 7;\n } while (remaining > 0);\n return count;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiImagePriceResponse } from \"../types\";\n\nexport function getAiGeneratePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.prices(),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-generate-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI generation prices: ${response.status}`);\n }\n\n return (await response.json()) as AiImagePriceResponse;\n },\n staleTime: 300_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiAssistPrice } from \"../types\";\n\nexport function getAiAssistPriceQueryOptions(username: string | undefined, accessToken: string) {\n return queryOptions({\n queryKey: QueryKeys.ai.assistPrices(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-assist-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI assist prices: ${response.status}`);\n }\n\n return (await response.json()) as AiAssistPrice[];\n },\n staleTime: 60_000,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"../../core\";\nimport type { AiTranscribePrice } from \"../types\";\n\n/**\n * Dictation pricing. Kept on its own route rather than folded into\n * /private-api/ai-assist-price: that endpoint returns a list of flat-cost actions and\n * shipped clients render every entry as a selectable assist action, so adding a\n * metered one there would surface in older clients as an action they cannot perform.\n *\n * Everything except `free_remaining` is static, so this is cheap to hold and lets the\n * client price a clip locally while the user is still recording.\n */\nexport function getAiTranscribePriceQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.ai.transcribePrice(username),\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch AI transcribe price: ${response.status}`);\n }\n\n return (await response.json()) as AiTranscribePrice;\n },\n staleTime: 60_000,\n enabled: !!accessToken\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiGenerationResponse } from \"../types\";\n\nexport interface GenerateImageParams {\n prompt: string;\n aspect_ratio?: string;\n power?: number;\n // Pass a stable key to make a retry recover the same paid generation. If omitted a\n // fresh key is generated per call (only dedupes edge/proxy retries, not user retries).\n idempotency_key?: string;\n}\n\n// Generates a key matching the eepoints validator [A-Za-z0-9_-]{8,64}.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useGenerateImage(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"generate-image\"],\n mutationFn: async (params: GenerateImageParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][GenerateImage] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-generate-image\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: accessToken,\n us: username,\n prompt: params.prompt,\n aspect_ratio: params.aspect_ratio ?? \"1:1\",\n power: params.power ?? 1,\n idempotency_key: params.idempotency_key ?? makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][GenerateImage] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n // 202 = the prediction is paid for and captured but not yet delivered to our image\n // host. Detect it by HTTP status BEFORE parsing (the body may be present or empty)\n // and surface it as a typed error so the caller can retry with the SAME\n // idempotency_key to fetch it — no second prediction, no second charge.\n if (response.status === 202) {\n let pendingData: Record = {};\n try {\n pendingData = await response.json();\n } catch {\n // empty / non-JSON 202 body is fine — the status alone drives recovery\n }\n const err = new Error(\"[SDK][AI][GenerateImage] – delivery pending\");\n (err as any).status = 202;\n (err as any).data = pendingData;\n throw err;\n }\n\n const data = (await response.json()) as AiGenerationResponse;\n\n return data;\n },\n onSuccess: () => {\n // Invalidate points cache since balance changed\n if (username) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiAssistResponse } from \"../types\";\n\nexport interface AiAssistParams {\n action: string;\n text: string;\n code?: string;\n}\n\n// Generates a key that matches the eepoints validator [A-Za-z0-9_-]{8,64}.\n// Used to dedupe duplicate POSTs caused by edge/proxy retries — same key on\n// retry returns the cached AI output without re-charging or re-calling Claude.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nexport function useAiAssist(\n username: string | undefined,\n accessToken: string | undefined,\n) {\n return useMutation({\n mutationKey: [\"ai\", \"assist\"],\n mutationFn: async (params: AiAssistParams): Promise => {\n if (!username) {\n throw new Error(\n \"[SDK][AI][Assist] – username wasn't provided\"\n );\n }\n\n if (!accessToken) {\n throw new Error(\n \"[SDK][AI][Assist] – access token wasn't found\"\n );\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/ai-assist\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code: params.code ?? accessToken,\n us: username,\n action: params.action,\n text: params.text,\n idempotency_key: makeIdempotencyKey(),\n }),\n }\n );\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n const err = new Error(\n `[SDK][AI][Assist] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n );\n (err as any).status = response.status;\n (err as any).data = parsed;\n throw err;\n }\n\n return (await response.json()) as AiAssistResponse;\n },\n onSuccess: (data) => {\n if (username) {\n // Invalidate points cache if cost was charged\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username),\n });\n }\n // Invalidate assist prices to refresh free_remaining counts\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.assistPrices(username),\n });\n }\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AiTranscribeParams, AiTranscribeResponse } from \"../types\";\n\n// Matches the eepoints validator [A-Za-z0-9_-]{8,64}. Dedupes duplicate POSTs caused\n// by edge/proxy retries -- the same key returns the cached transcript without\n// re-charging or re-calling the vendor.\nfunction makeIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const arr = new Uint8Array(16);\n if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n crypto.getRandomValues(arr);\n } else {\n for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);\n }\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Transcribe an audio clip to text, charged per 30 seconds.\n *\n * Sends multipart/form-data rather than JSON because it carries a file. Unlike the\n * other AI mutations the charge is BURNED rather than moved to the treasury, so the\n * points transaction shows up as PointTransactionType.BURNED (997).\n */\nexport function useAiTranscribe(username: string | undefined, accessToken: string | undefined) {\n return useMutation({\n mutationKey: [\"ai\", \"transcribe\"],\n mutationFn: async (params: AiTranscribeParams): Promise => {\n if (!username) {\n throw new Error(\"[SDK][AI][Transcribe] – username wasn't provided\");\n }\n\n // Validate the token actually being sent, not just the bound one. A caller\n // that resolves a fresh token per call (because the bound one can expire\n // during a long recording) legitimately has nothing at hook construction.\n const code = params.code ?? accessToken;\n if (!code) {\n throw new Error(\"[SDK][AI][Transcribe] – access token wasn't found\");\n }\n\n const form = new FormData();\n form.append(\"code\", code);\n // `us` is resolved from the code server-side and is deliberately not sent:\n // upstream burns from whoever it names.\n form.append(\"duration_ms\", String(Math.round(params.durationMs)));\n // Caller-supplied key when there is one. Generating a fresh key per attempt\n // would defeat the dedupe in the one case it exists for: a POST that reached\n // the server whose response was lost. Retrying then would transcribe and\n // charge a second time. Same contract as useGenerateImage.\n form.append(\"idempotency_key\", params.idempotency_key ?? makeIdempotencyKey());\n form.append(\"audio\", params.audio, params.fileName ?? \"clip.webm\");\n\n const fetchApi = getBoundFetch();\n // No Content-Type header: fetch sets it, including the multipart boundary.\n // Setting it by hand drops the boundary and the body becomes unparseable.\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/ai-transcribe\", {\n method: \"POST\",\n body: form\n });\n\n if (!response.ok) {\n const body = await response.text();\n let parsed: Record = {};\n try {\n parsed = JSON.parse(body);\n } catch {\n // not JSON\n }\n\n // Object.assign rather than `as any` casts: callers need `status` to tell a\n // 402 (out of Points) from a 429 (rate limited) from a 400 (clip too long),\n // and this keeps that shape typed.\n throw Object.assign(\n new Error(\n `[SDK][AI][Transcribe] – failed with status ${response.status}${body ? `: ${body}` : \"\"}`\n ),\n { status: response.status, data: parsed }\n );\n }\n\n return (await response.json()) as AiTranscribeResponse;\n },\n onSuccess: (data) => {\n if (username) {\n if (data.cost > 0) {\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.points._prefix(username)\n });\n }\n // Refresh free_remaining, which only Pro members ever have above zero.\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.ai.transcribePrice(username)\n });\n }\n }\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport {\n AccountFollowStats,\n FullAccount,\n} from \"../types\";\nimport { parseProfileMetadata } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** The raw `condenser_api.get_accounts` row — every FullAccount field except the three\n * this query derives separately (follow_stats + reputation from bridge, profile parsed). */\ntype RawAccount = Omit;\n\n/** Minimal shape read from `bridge.get_profile` (hivemind social profile): it carries\n * the reputation score, the follower/following counts and hivemind's parsed\n * (normalized) profile — the latter is used only to cross-validate the chain row. */\ninterface BridgeProfile {\n reputation?: number;\n stats?: { followers?: number; following?: number };\n metadata?: { profile?: Record };\n}\n\n/** True when the chain row carries no account metadata at all. Legitimate for\n * accounts that never set a profile — but combined with a populated hivemind\n * profile it identifies a node serving stripped account rows. */\nfunction isMetadataStripped(account: RawAccount): boolean {\n return !account.posting_json_metadata && !account.json_metadata;\n}\n\n/** True when a hivemind `metadata.profile` object carries at least one real\n * value. Hivemind emits its fixed profile keys with empty strings for\n * accounts without a profile, so key presence alone proves nothing. */\nfunction hasProfileValues(profile?: Record | null): boolean {\n if (!profile) return false;\n return Object.values(profile).some((value) =>\n typeof value === \"string\" ? value.length > 0 : value != null\n );\n}\n\nexport function getAccountFullQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.full(username),\n queryFn: async ({ signal }) => {\n if (!username) {\n return null;\n }\n\n // Fetch the chain account (balances/keys/vesting) and the hivemind profile in\n // parallel — both only need the username. bridge.get_profile carries BOTH the\n // follower/following counts and the reputation score, so it replaces the old\n // second-layer condenser_api.get_follow_count RPC *and* the reputation-api REST\n // call: condenser_api.get_accounts no longer returns a usable reputation (it is 0\n // since the hardfork), and there is no reason to make two extra round-trips for\n // data one profile object already carries.\n const [response, bridgeProfile] = await Promise.all([\n callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so fail over to the next node instead of misreading it as\n // \"account does not exist\".\n (rows) => Array.isArray(rows)\n ),\n callRPC(\n \"bridge.get_profile\",\n { account: username },\n undefined,\n undefined,\n signal\n ).catch((e): BridgeProfile | null => {\n // A caller cancel (aborted signal) must propagate — only genuine RPC/transport\n // failures degrade to reputation 0 / no follow_stats.\n if (signal?.aborted) throw e;\n return null;\n })\n ]);\n if (!response?.[0]) {\n // The account does not exist (e.g. not yet finalized on-chain during\n // signup). Treat absence as a recoverable null instead of throwing, so\n // consumers (useQuery hooks and fetchQuery callers) surface it as empty\n // data rather than an unhandled rejection / error-boundary crash.\n return null;\n }\n\n let chainAccount = response[0];\n\n // Cross-validate the chain row against the hivemind profile fetched in\n // the same query. Some public nodes serve account rows with BOTH\n // metadata fields stripped to \"\" (observed in the wild) while their own\n // hivemind still returns the real profile — and a merge base built from\n // such a row wipes the user's profile on the next partial\n // account_update2. When the row claims \"no metadata\" but hivemind\n // disagrees, re-read once (failover may pick another node) and otherwise\n // fail the query: an error here is recoverable, a poisoned cache entry\n // is not.\n if (\n isMetadataStripped(chainAccount) &&\n hasProfileValues(bridgeProfile?.metadata?.profile)\n ) {\n // The re-read carries a payload validator: a stripped row is treated\n // as a node fault, so the failover walk moves on to other nodes (and\n // repeat offenders earn a per-API health cooldown) instead of asking\n // the same lying node twice.\n const reread = await callRPC(\n \"condenser_api.get_accounts\",\n [[username]],\n undefined,\n undefined,\n signal,\n (rows) =>\n Array.isArray(rows) &&\n (!rows[0] || !isMetadataStripped(rows[0] as RawAccount))\n );\n if (reread[0] && !isMetadataStripped(reread[0])) {\n chainAccount = reread[0];\n } else {\n throw new Error(\n `[SDK][Accounts] – inconsistent account row for ${username}: empty json metadata while hivemind profile is populated`\n );\n }\n }\n\n const profile = parseProfileMetadata(chainAccount.posting_json_metadata);\n\n // bridge.get_profile.stats → follower/following counts; `reputation` is the\n // computed score (e.g. 78.29). accountReputation() floors an in-range score, so\n // it yields the same value the reputation-api used to return. Both degrade to a\n // safe default if the profile call failed.\n const stats = bridgeProfile?.stats;\n const follow_stats: AccountFollowStats | undefined = stats\n ? {\n account: chainAccount.name,\n follower_count: stats.followers ?? 0,\n following_count: stats.following ?? 0\n }\n : undefined;\n const reputationValue: number = bridgeProfile?.reputation ?? 0;\n\n return {\n name: chainAccount.name,\n owner: chainAccount.owner,\n active: chainAccount.active,\n posting: chainAccount.posting,\n memo_key: chainAccount.memo_key,\n post_count: chainAccount.post_count,\n created: chainAccount.created,\n posting_json_metadata: chainAccount.posting_json_metadata,\n last_vote_time: chainAccount.last_vote_time,\n last_post: chainAccount.last_post,\n json_metadata: chainAccount.json_metadata,\n reward_hive_balance: chainAccount.reward_hive_balance,\n reward_hbd_balance: chainAccount.reward_hbd_balance,\n reward_vesting_hive: chainAccount.reward_vesting_hive,\n reward_vesting_balance: chainAccount.reward_vesting_balance,\n balance: chainAccount.balance,\n hbd_balance: chainAccount.hbd_balance,\n savings_balance: chainAccount.savings_balance,\n savings_hbd_balance: chainAccount.savings_hbd_balance,\n savings_hbd_last_interest_payment:\n chainAccount.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update:\n chainAccount.savings_hbd_seconds_last_update,\n savings_hbd_seconds: chainAccount.savings_hbd_seconds,\n next_vesting_withdrawal: chainAccount.next_vesting_withdrawal,\n pending_claimed_accounts: chainAccount.pending_claimed_accounts,\n vesting_shares: chainAccount.vesting_shares,\n delegated_vesting_shares: chainAccount.delegated_vesting_shares,\n received_vesting_shares: chainAccount.received_vesting_shares,\n vesting_withdraw_rate: chainAccount.vesting_withdraw_rate,\n to_withdraw: chainAccount.to_withdraw,\n withdrawn: chainAccount.withdrawn,\n witness_votes: chainAccount.witness_votes,\n proxy: chainAccount.proxy,\n recovery_account: chainAccount.recovery_account,\n proxied_vsf_votes: chainAccount.proxied_vsf_votes,\n voting_manabar: chainAccount.voting_manabar,\n voting_power: chainAccount.voting_power,\n downvote_manabar: chainAccount.downvote_manabar,\n follow_stats,\n reputation: reputationValue,\n profile,\n } satisfies FullAccount;\n },\n enabled: !!username,\n staleTime: 60000,\n });\n}\n","import { AccountProfile, FullAccount } from \"../types\";\n\nexport type ProfileTokens = AccountProfile[\"tokens\"];\n\nconst DENIED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isPlainObject(value: unknown): value is Record {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction deepMerge>(target: T, source: Record): T {\n const result = { ...target } as Record;\n for (const key of Object.keys(source)) {\n if (DENIED_KEYS.has(key)) {\n continue;\n }\n const srcVal = source[key];\n const tgtVal = result[key];\n if (isPlainObject(srcVal) && isPlainObject(tgtVal)) {\n result[key] = deepMerge(tgtVal, srcVal);\n } else {\n result[key] = srcVal;\n }\n }\n return result as T;\n}\n\nexport interface BuildProfileMetadataArgs {\n existingProfile?: AccountProfile;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}\n\nfunction sanitizeTokens(\n tokens?: ProfileTokens | null\n): ProfileTokens | undefined {\n // Guard against corrupted data from blockchain where tokens is not an array\n if (!tokens || !Array.isArray(tokens)) {\n return undefined;\n }\n\n return tokens.map(({ meta, ...rest }) => {\n if (!meta || typeof meta !== \"object\") {\n return { ...rest, meta };\n }\n\n const { privateKey, username, ...safeMeta } = meta;\n return { ...rest, meta: safeMeta };\n });\n}\n\nexport function parseProfileMetadata(\n postingJsonMetadata?: string | null\n): AccountProfile {\n if (!postingJsonMetadata) {\n return {} as AccountProfile;\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n parsed.profile &&\n typeof parsed.profile === \"object\"\n ) {\n return parsed.profile as AccountProfile;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata:\", err, { length: postingJsonMetadata?.length ?? 0 });\n }\n\n return {} as AccountProfile;\n}\n\nexport function extractAccountProfile(\n data?: Pick | null\n): AccountProfile {\n return parseProfileMetadata(data?.posting_json_metadata);\n}\n\n/**\n * Choose between two account snapshots for a posting-metadata merge base.\n * Prefers `preferred` (typically the freshest cache entry) unless `fallback`\n * carries strictly more profile keys — guarding read-modify-write flows\n * against a snapshot whose metadata was served stripped by a misbehaving node\n * while another snapshot still holds the real profile. A partial update must\n * never shrink the profile while any snapshot still knows the full one.\n */\nexport function pickRicherMetadataSnapshot<\n T extends Pick\n>(\n preferred: T | null | undefined,\n fallback: T | null | undefined\n): T | null | undefined {\n if (!preferred) return fallback;\n if (!fallback) return preferred;\n const preferredKeys = Object.keys(\n parseProfileMetadata(preferred.posting_json_metadata)\n ).length;\n const fallbackKeys = Object.keys(\n parseProfileMetadata(fallback.posting_json_metadata)\n ).length;\n return fallbackKeys > preferredKeys ? fallback : preferred;\n}\n\n/**\n * Parse the FULL root object of posting_json_metadata, not just its `profile`\n * key. Returns {} for missing/invalid input or a non-object root.\n *\n * `parseProfileMetadata` intentionally returns only `parsed.profile`; this\n * helper exists so writers can carry forward any sibling top-level keys that\n * live alongside `profile` (data other Hive apps may store there) instead of\n * dropping them on the next update.\n */\nexport function parsePostingMetadataRoot(\n postingJsonMetadata?: string | null\n): Record {\n if (!postingJsonMetadata) {\n return {};\n }\n\n try {\n const parsed = JSON.parse(postingJsonMetadata);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n } catch (err) {\n console.warn(\"[SDK] Failed to parse posting_json_metadata root:\", err, {\n length: postingJsonMetadata?.length ?? 0,\n });\n }\n\n return {};\n}\n\n/**\n * Build the serialized `posting_json_metadata` string for an account_update2\n * operation. It deep-merges the profile (via {@link buildProfileMetadata}) over\n * the account's CURRENT on-chain profile AND preserves any non-`profile`\n * top-level keys present in the existing metadata, so a partial profile update\n * (e.g. only `pinned` or only `tokens`) never clobbers unrelated fields.\n */\nexport function buildPostingJsonMetadata({\n existingPostingJsonMetadata,\n profile,\n tokens,\n}: {\n existingPostingJsonMetadata?: string | null;\n profile?: Partial | null;\n tokens?: ProfileTokens | null;\n}): string {\n const root = parsePostingMetadataRoot(existingPostingJsonMetadata);\n const existingProfile = isPlainObject(root.profile)\n ? (root.profile as AccountProfile)\n : ({} as AccountProfile);\n\n const mergedProfile = buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n });\n\n return JSON.stringify({ ...root, profile: mergedProfile });\n}\n\nexport function buildProfileMetadata({\n existingProfile,\n profile,\n tokens,\n}: BuildProfileMetadataArgs): AccountProfile {\n const { tokens: profileTokens, version: _ignoredVersion, ...profileRest } =\n profile ?? {};\n\n const metadata = deepMerge(\n (existingProfile ?? {}) as Record,\n profileRest as Record,\n ) as AccountProfile;\n\n // Clean up corrupted tokens data from blockchain before processing\n if (metadata.tokens && !Array.isArray(metadata.tokens)) {\n metadata.tokens = undefined;\n }\n\n // tokens semantics:\n // undefined → no change, fall back to profileTokens from profile partial\n // null or [] → explicitly clear tokens\n // non-empty array → set tokens\n if (tokens !== undefined) {\n // Explicit intent from caller: null or [] clears, non-empty array sets\n metadata.tokens = tokens && tokens.length > 0 ? tokens : [];\n } else if (profileTokens !== undefined) {\n // Fall back to tokens from profile partial (including empty array to clear)\n metadata.tokens = profileTokens;\n }\n\n metadata.tokens = sanitizeTokens(metadata.tokens);\n metadata.version = 2;\n\n return metadata;\n}\n","import { FullAccount, AccountProfile } from \"../types\";\nimport { parseProfileMetadata } from \"./profile-metadata\";\n\n/**\n * Parses raw account data from Hive API into FullAccount type\n * Handles profile metadata extraction from posting_json_metadata or json_metadata\n */\nexport function parseAccounts(rawAccounts: any[]): FullAccount[] {\n return rawAccounts.map((x) => {\n const account: FullAccount = {\n name: x.name,\n owner: x.owner,\n active: x.active,\n posting: x.posting,\n memo_key: x.memo_key,\n post_count: x.post_count,\n created: x.created,\n reputation: x.reputation,\n posting_json_metadata: x.posting_json_metadata,\n last_vote_time: x.last_vote_time,\n last_post: x.last_post,\n json_metadata: x.json_metadata,\n reward_hive_balance: x.reward_hive_balance,\n reward_hbd_balance: x.reward_hbd_balance,\n reward_vesting_hive: x.reward_vesting_hive,\n reward_vesting_balance: x.reward_vesting_balance,\n balance: x.balance,\n hbd_balance: x.hbd_balance,\n savings_balance: x.savings_balance,\n savings_hbd_balance: x.savings_hbd_balance,\n savings_hbd_last_interest_payment: x.savings_hbd_last_interest_payment,\n savings_hbd_seconds_last_update: x.savings_hbd_seconds_last_update,\n savings_hbd_seconds: x.savings_hbd_seconds,\n next_vesting_withdrawal: x.next_vesting_withdrawal,\n pending_claimed_accounts: x.pending_claimed_accounts,\n vesting_shares: x.vesting_shares,\n delegated_vesting_shares: x.delegated_vesting_shares,\n received_vesting_shares: x.received_vesting_shares,\n vesting_withdraw_rate: x.vesting_withdraw_rate,\n to_withdraw: x.to_withdraw,\n withdrawn: x.withdrawn,\n witness_votes: x.witness_votes,\n proxy: x.proxy,\n recovery_account: x.recovery_account,\n proxied_vsf_votes: x.proxied_vsf_votes,\n voting_manabar: x.voting_manabar,\n voting_power: x.voting_power,\n downvote_manabar: x.downvote_manabar,\n };\n\n // Try to parse profile from posting_json_metadata first\n let profile: AccountProfile | undefined = parseProfileMetadata(\n x.posting_json_metadata\n );\n\n // Fallback to json_metadata if posting_json_metadata didn't have a profile\n if (!profile || Object.keys(profile).length === 0) {\n try {\n const jsonMetadata = JSON.parse(x.json_metadata || \"{}\");\n if (jsonMetadata.profile) {\n profile = jsonMetadata.profile;\n }\n } catch (e) {\n // Ignore parsing errors\n }\n }\n\n // Ensure we always have a profile object\n if (!profile || Object.keys(profile).length === 0) {\n profile = {\n about: \"\",\n cover_image: \"\",\n location: \"\",\n name: \"\",\n profile_image: \"\",\n website: \"\",\n };\n }\n\n return { ...account, profile };\n });\n}\n","/**\n * The chain stores an account name in a `fixed_string` of 16 **bytes**, and hived\n * asserts on the byte length while deserialising the argument, before it ever looks\n * an account up. So a name that is too long does not come back as \"no such account\",\n * it comes back as\n *\n * Assert Exception:in_len <= sizeof(data): Input too large: `` (17)\n * for fixed size string: (16)\n *\n * from `lookup_accounts`, `get_accounts` and anything else taking an\n * `account_name_type`, including plain reads.\n */\nconst HIVE_ACCOUNT_NAME_MAX_BYTES = 16;\n\n/**\n * Bytes, not characters. The two differ exactly where this bug lives: `sebastián.bilbao`\n * is 16 characters but 17 bytes, and `вцпк33ппп43` is 11 characters but 18 bytes. Both\n * pass a `.length <= 16` check and both are rejected by the node.\n */\nexport function accountNameByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Whether a value can be sent to a node as an account name (or as the prefix of one,\n * which `lookup_accounts` takes) without tripping the assert above.\n *\n * This is deliberately only a length check. It is not account-name validation: a\n * caller searching for a prefix is allowed to pass something that is not yet a legal\n * name, and a node answers that honestly with no matches. The only thing that must not\n * happen is a request the node refuses to parse.\n */\nexport function isQueryableAccountName(value: string | undefined | null): boolean {\n if (!value) {\n return false;\n }\n\n return accountNameByteLength(value) <= HIVE_ACCOUNT_NAME_MAX_BYTES;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { parseAccounts } from \"../utils/parse-accounts\";\nimport { FullAccount } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountsQueryOptions(usernames: string[]) {\n return queryOptions({\n queryKey: QueryKeys.accounts.list(...usernames),\n enabled: usernames.length > 0,\n queryFn: async (): Promise => {\n // One unholdable name asserts the whole batch, so drop those first. They\n // cannot name an existing account, and an empty result is what a caller\n // checking \"does this account exist\" already handles.\n const queryable = usernames.filter(isQueryableAccountName);\n if (queryable.length === 0) {\n return [];\n }\n\n // A correct node always answers get_accounts with an array — a null\n // result in a well-formed envelope is a node fault (observed in the\n // wild), so the validator makes callRPC fail over to the next node\n // instead of resolving with a payload parseAccounts cannot map over.\n const response = (await callRPC(\n \"condenser_api.get_accounts\",\n [queryable],\n undefined,\n undefined,\n undefined,\n (rows) => Array.isArray(rows)\n )) as any[];\n return parseAccounts(response ?? []);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountFollowStats } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get follow count (followers and following) for an account\n */\nexport function getFollowCountQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followCount(username),\n queryFn: () =>\n callRPC(\"condenser_api.get_follow_count\", [\n username,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts following a user\n *\n * @param following - The account being followed\n * @param startFollower - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowersQueryOptions(\n following: string | undefined,\n startFollower: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.followers(following!, startFollower, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_followers\", [\n following,\n startFollower,\n followType,\n limit,\n ]) as Promise,\n enabled: !!following,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of accounts that a user is following\n *\n * @param follower - The account doing the following\n * @param startFollowing - Pagination start point (account name)\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Maximum number of results (default: 100)\n */\nexport function getFollowingQueryOptions(\n follower: string,\n startFollowing: string,\n followType = \"blog\",\n limit = 100\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.following(follower, startFollowing, followType, limit),\n queryFn: () =>\n callRPC(\"condenser_api.get_following\", [\n follower,\n startFollowing,\n followType,\n limit,\n ]) as Promise,\n enabled: !!follower,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/** `condenser_api.get_following` caps a single response at 1000 rows. */\nconst MUTED_USERS_PAGE_SIZE = 1000;\n\n/**\n * Safety valve for the paging loop: 20 pages is 20k muted accounts, far past\n * any real mute list. Bounds the work if a node ever stops advancing the\n * cursor, so a malformed response degrades to a truncated list rather than an\n * endless request loop.\n */\nconst MUTED_USERS_MAX_PAGES = 20;\n\n/**\n * Get the full list of accounts a user has muted.\n *\n * Pages until the list is exhausted instead of taking the first N. That is\n * load-bearing: this result dims muted authors in feeds and collapses their\n * comments (`entry-list-item-muted-content`, `discussion-list`), so a truncated\n * list silently renders muted accounts as though they were never muted.\n *\n * Takes no limit, on purpose. `QueryKeys.accounts.mutedUsers` keys on the\n * username alone, so a limit parameter meant callers requesting different\n * amounts shared one cache entry and whichever mounted first decided how much\n * of the list every other caller saw.\n *\n * @param username - The account whose mute list to fetch\n */\nexport function getMutedUsersQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: QueryKeys.accounts.mutedUsers(username!),\n queryFn: async () => {\n const muted: string[] = [];\n let start = \"\";\n\n for (let page = 0; page < MUTED_USERS_MAX_PAGES; page++) {\n const response = (await callRPC(\"condenser_api.get_following\", [\n username,\n start,\n \"ignore\",\n MUTED_USERS_PAGE_SIZE,\n ])) as Follow[];\n\n if (!response?.length) {\n break;\n }\n\n let names = response.map((user) => user.following);\n\n // `start` is exclusive on Hive, so a page should not repeat the cursor.\n // Drop it defensively anyway: against a node treating `start` as\n // inclusive, this loop would otherwise re-append the same account until\n // it hit the page cap.\n if (names[0] === start) {\n names = names.slice(1);\n }\n\n if (!names.length) {\n break;\n }\n\n muted.push(...names);\n\n if (response.length < MUTED_USERS_PAGE_SIZE) {\n break;\n }\n\n start = names[names.length - 1];\n }\n\n return muted;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\n/**\n * Lookup accounts by username prefix\n *\n * @param query - Username prefix to search for\n * @param limit - Maximum number of results (default: 50)\n */\nexport function lookupAccountsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.lookup(query, limit),\n queryFn: async (): Promise => {\n // `lower_bound_name` is an account_name_type, so a prefix the chain cannot\n // hold is an assert rather than an empty result. Callers feed this from raw\n // input (the editor's `@` autocomplete hands over whatever follows the `@`,\n // punctuation included), so answer \"nothing matches\" here instead.\n if (!isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.lookup_accounts\", [\n query,\n limit,\n ]) as Promise;\n },\n enabled: !!query,\n staleTime: Infinity,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountsByUsernameQueryOptions(\n query: string,\n limit = 5,\n excludeList: string[] = []\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.search(query, excludeList),\n enabled: !!query,\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.lookup_accounts\", [query, limit])) as string[];\n return response.filter((item) =>\n excludeList.length > 0 ? !excludeList.includes(item) : true\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountProfile } from \"../types\";\n\ntype AccountProfileToken = NonNullable[number];\n\nexport type WalletMetadataCandidate = Partial & {\n currency?: string;\n show?: boolean;\n address?: string;\n publicKey?: string;\n privateKey?: string;\n username?: string;\n};\n\nexport interface CheckUsernameWalletsPendingResponse {\n exist: boolean;\n tokens?: WalletMetadataCandidate[];\n wallets?: WalletMetadataCandidate[];\n}\n\nconst RESERVED_META_KEYS = new Set([\n \"ownerPublicKey\",\n \"activePublicKey\",\n \"postingPublicKey\",\n \"memoPublicKey\",\n]);\n\ninterface WalletsEndpointResponseItem {\n token?: unknown;\n address?: unknown;\n status?: unknown;\n meta?: unknown;\n username?: unknown;\n}\n\nexport function checkUsernameWalletsPendingQueryOptions(\n username: string,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkWalletPending(username, code ?? null),\n queryFn: async () => {\n if (!username || !code) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/wallets\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n code,\n }),\n }\n );\n\n if (!response.ok) {\n return { exist: false } satisfies CheckUsernameWalletsPendingResponse;\n }\n\n const payload = (await response.json()) as unknown;\n\n const wallets: WalletMetadataCandidate[] = Array.isArray(payload)\n ? payload.flatMap((item) => {\n if (!item || typeof item !== \"object\") {\n return [];\n }\n\n const walletItem = item as WalletsEndpointResponseItem;\n\n const symbol =\n typeof walletItem.token === \"string\"\n ? walletItem.token\n : undefined;\n\n if (!symbol) {\n return [];\n }\n\n const meta: Record =\n walletItem.meta && typeof walletItem.meta === \"object\"\n ? { ...(walletItem.meta as Record) }\n : {};\n\n const sanitizedMeta: Record = {};\n\n const address =\n typeof walletItem.address === \"string\" && walletItem.address\n ? walletItem.address\n : undefined;\n\n const statusShow =\n typeof walletItem.status === \"number\"\n ? walletItem.status === 3\n : undefined;\n\n const showFlag = statusShow ?? false;\n\n if (address) {\n sanitizedMeta.address = address;\n }\n\n sanitizedMeta.show = showFlag;\n\n const baseCandidate = {\n symbol,\n currency: symbol,\n address,\n show: showFlag,\n type: \"CHAIN\",\n meta: sanitizedMeta,\n } satisfies WalletMetadataCandidate;\n\n const metaTokenCandidates: WalletMetadataCandidate[] = [];\n\n for (const [metaSymbol, metaValue] of Object.entries(meta)) {\n if (typeof metaSymbol !== \"string\") {\n continue;\n }\n\n if (RESERVED_META_KEYS.has(metaSymbol)) {\n continue;\n }\n\n if (typeof metaValue !== \"string\" || !metaValue) {\n continue;\n }\n\n if (!/^[A-Z0-9]{2,10}$/.test(metaSymbol)) {\n continue;\n }\n\n metaTokenCandidates.push({\n symbol: metaSymbol,\n currency: metaSymbol,\n address: metaValue,\n show: showFlag,\n type: \"CHAIN\",\n meta: { address: metaValue, show: showFlag },\n });\n }\n\n return [baseCandidate, ...metaTokenCandidates];\n })\n : [];\n\n return {\n exist: wallets.length > 0,\n tokens: wallets.length ? wallets : undefined,\n wallets: wallets.length ? wallets : undefined,\n } satisfies CheckUsernameWalletsPendingResponse;\n },\n refetchOnMount: true,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { AccountRelationship } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRelationshipBetweenAccountsQueryOptions(\n reference: string | undefined,\n target: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.relations(reference, target),\n enabled: !!reference && !!target,\n refetchOnMount: false,\n refetchInterval: 3_600_000,\n queryFn: async () => {\n const fallback: AccountRelationship = {\n follows: false,\n ignores: false,\n blacklists: false,\n follows_muted: false,\n follows_blacklists: false,\n };\n\n // `enabled` only gates the automatic useQuery run. fetchQuery and\n // prefetchQuery invoke queryFn regardless, so guard here as well rather\n // than sending a missing account name to the RPC and caching the result.\n if (!reference || !target) {\n return fallback;\n }\n\n const result = await callRPC(\"bridge.get_relationship_between_accounts\", [reference, target]);\n return (result ?? fallback) as AccountRelationship;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype Subscriptions = string[];\n\nexport function getAccountSubscriptionsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.subscriptions(username!),\n enabled: !!username,\n queryFn: async ({ signal }) => {\n const response = await callRPC(\"bridge.list_all_subscriptions\", {\n account: username,\n }, undefined, undefined, signal);\n return (response ?? []) as Subscriptions;\n },\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountBookmark } from \"../types\";\n\nexport function getBookmarksQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.bookmarks(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Bookmarks] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountBookmark[];\n },\n });\n}\n\nexport function getBookmarksInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.bookmarksInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bookmarks: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../types\";\n\nexport function getFavoritesQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.favorites(activeUsername),\n enabled: !!activeUsername && !!code,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n return (await response.json()) as AccountFavorite[];\n },\n });\n}\n\nexport function getFavoritesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.favoritesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/favorites?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch favorites: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n/**\n * Query options to check if a specific account is in the active user's favorites\n * @param activeUsername - The logged-in user's username\n * @param code - Access token for authentication\n * @param targetUsername - The username to check if favorited\n * @returns Query options for checking if target is favorited\n */\nexport function checkFavoriteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n targetUsername: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.checkFavorite(activeUsername!, targetUsername!),\n enabled: !!activeUsername && !!code && !!targetUsername,\n queryFn: async () => {\n if (!activeUsername || !code) {\n throw new Error(\"[SDK][Accounts][Favorites] – missing auth\");\n }\n if (!targetUsername) {\n throw new Error(\"[SDK][Accounts][Favorites] – no target username\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-check\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n account: targetUsername,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check failed with status ${response.status}: ${response.statusText}`\n );\n }\n\n const result = await response.json();\n if (typeof result !== \"boolean\") {\n throw new Error(\n `[SDK][Accounts][Favorites] – favorites-check returned invalid type: expected boolean, got ${typeof result}`\n );\n }\n\n return result;\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetRecoveriesEmailResponse } from \"../types\";\n\nexport function getAccountRecoveriesQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n enabled: !!username && !!code,\n queryKey: QueryKeys.accounts.recoveries(username!),\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Accounts] Missing username or access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/recoveries\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n }\n );\n\n return response.json() as Promise;\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getAccountPendingRecoveryQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n enabled: !!username,\n queryKey: QueryKeys.accounts.pendingRecovery(username!),\n queryFn: () =>\n callRPC(\"database_api.find_change_recovery_account_requests\", { accounts: [username] }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountReputation } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { isQueryableAccountName } from \"../utils/account-name-query\";\n\nexport function getAccountReputationsQueryOptions(query: string, limit = 50) {\n return queryOptions({\n queryKey: QueryKeys.accounts.reputations(query, limit),\n enabled: !!query,\n queryFn: async (): Promise => {\n // Same account_name_type argument as lookup_accounts, same assert if the value\n // is longer than the chain can hold.\n if (!query || !isQueryableAccountName(query)) {\n return [];\n }\n\n return callRPC(\"condenser_api.get_account_reputations\", [query, limit]) as Promise;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { utils } from \"../../../hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Transaction, OperationGroup } from \"../types/transaction\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { parseAsset, NaiMap } from \"@/modules/core/utils\";\n\nconst ops = utils.operations;\n\nexport const ACCOUNT_OPERATION_GROUPS: Record = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n // The virtual op emitted when a savings withdrawal completes. It used to be a\n // second copy of fill_recurrent_transfer, so a completed savings withdrawal was\n // never returned by the transfers group nor by ALL_ACCOUNT_OPERATIONS.\n ops.fill_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n};\n\n/**\n * Every operation any group asks for, de-duplicated. Groups overlap (an op can be\n * meaningful to more than one), and the raw concatenation used to repeat ids in the\n * `operation-types` query string sent to hafah.\n */\nexport const ALL_ACCOUNT_OPERATIONS = Array.from(\n new Set(Object.values(ACCOUNT_OPERATION_GROUPS).flat())\n);\n\ninterface TxPageRaw {\n entries: Transaction[];\n currentPage: number;\n}\n\n/**\n * Cursor for transaction pagination.\n * null = first request (returns newest page, API omits page param).\n * number = specific page to fetch (decrementing for older data).\n */\ntype TxCursor = number | null;\n\ninterface HafahOperation {\n op: {\n type: string;\n value: Record;\n };\n block: number;\n trx_id: string;\n op_pos: number;\n op_type_id: number;\n timestamp: string;\n virtual_op: boolean;\n operation_id: string;\n trx_in_block: number;\n}\n\ninterface HafahResponse {\n total_operations: number;\n total_pages: number;\n operations_result: HafahOperation[];\n}\n\n/**\n * Derive a safe, unique, and chronologically ordered `num` from REST fields.\n *\n * Layout: block * 10_000_000 + trx_in_block * 100 + op_pos\n * - trx_in_block: up to 99_999 (Hive max block size ~65K txs)\n * - op_pos: up to 99 (operations within a single transaction)\n * - Max value: 105_000_000 * 10_000_000 = 1.05e15, within MAX_SAFE_INTEGER (9.007e15)\n */\nfunction deriveNum(entry: HafahOperation): number {\n return entry.block * 10_000_000 + entry.trx_in_block * 100 + entry.op_pos;\n}\n\n/**\n * Strip the `_operation` suffix from the REST API type name\n * to match the Transaction type discriminants (e.g. \"transfer\").\n */\nfunction normalizeOpType(restType: string): string {\n return restType.replace(/_operation$/, \"\");\n}\n\n/**\n * Check if a value is a NAI asset object (e.g. { nai: \"@@000000021\", amount: \"1000\", precision: 3 }).\n */\nfunction isNaiAsset(v: unknown): v is { nai: string; amount: string; precision: number } {\n return typeof v === \"object\" && v !== null && \"nai\" in v && \"amount\" in v && \"precision\" in v;\n}\n\n/**\n * Convert a NAI asset object to a human-readable string like \"1.000 HIVE\".\n * Returns the value unchanged if it's not a NAI object.\n */\nfunction naiToString(v: unknown): unknown {\n if (!isNaiAsset(v)) return v;\n const parsed = parseAsset(v);\n const symbol = NaiMap[v.nai as keyof typeof NaiMap] ?? \"UNKNOWN\";\n return `${parsed.amount.toFixed(v.precision)} ${symbol}`;\n}\n\n/**\n * Convert all NAI asset objects in an operation's value to human-readable strings\n * so downstream renderers that expect \"1.000 HIVE\" don't crash with object values.\n */\nfunction normalizeOpValue(value: Record): Record {\n const result: Record = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = naiToString(v);\n }\n return result;\n}\n\n/**\n * Get account transaction history with pagination and filtering.\n * Uses the hafah-api REST endpoint for server-side op-type filtering\n * and real pagination metadata.\n *\n * @param username - Account name to get transactions for\n * @param limit - Number of transactions per page\n * @param group - Filter by operation group (transfers, market-orders, etc.)\n */\nexport function getTransactionsInfiniteQueryOptions(\n username?: string,\n limit = 20,\n group: OperationGroup | \"\" = \"\"\n) {\n const operationTypes = group\n ? ACCOUNT_OPERATION_GROUPS[group]\n : ALL_ACCOUNT_OPERATIONS;\n\n return infiniteQueryOptions<\n TxPageRaw,\n Error,\n InfiniteData,\n (string | number)[],\n TxCursor\n >({\n queryKey: QueryKeys.accounts.transactions(username ?? \"\", group, limit),\n initialPageParam: null as TxCursor,\n\n queryFn: async ({ pageParam, signal }: { pageParam: TxCursor; signal?: AbortSignal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const fetchPage = async (page: TxCursor) => {\n const params: Record = {\n \"account-name\": username,\n \"operation-types\": operationTypes.join(\",\"),\n \"page-size\": limit,\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number (decrementing)\n if (page !== null) {\n params.page = page;\n }\n\n return (await callREST(\n \"hafah\",\n \"/accounts/{account-name}/operations\",\n params,\n undefined,\n undefined,\n signal\n )) as HafahResponse;\n };\n\n const toEntries = (response: HafahResponse) =>\n response.operations_result.map((entry) => {\n const type = normalizeOpType(entry.op.type);\n const value = normalizeOpValue(entry.op.value);\n return {\n ...value,\n num: deriveNum(entry),\n type,\n timestamp: entry.timestamp,\n trx_id: entry.trx_id,\n } as Transaction;\n });\n\n const response = await fetchPage(pageParam);\n let entries = toEntries(response);\n let currentPage = pageParam ?? response.total_pages;\n\n // hafah pages oldest-first, so the newest page (what an omitted `page`\n // returns) is the remainder bucket: total_operations mod page-size rows,\n // anywhere from 1 to page-size. Requesting page=total_pages explicitly\n // returns the same short bucket, so the only way to a full-size first\n // screen is chaining the next older page in.\n if (pageParam === null && entries.length < limit && response.total_pages > 1) {\n try {\n const chained = await fetchPage(response.total_pages - 1);\n entries = [...entries, ...toEntries(chained)];\n currentPage = response.total_pages - 1;\n } catch (e) {\n // Caller cancellation is not a node failure: rethrow so the query\n // settles as cancelled instead of resolving with a partial page.\n if (signal?.aborted) {\n throw e;\n }\n // Keep the short remainder page; the cursor stays at total_pages so\n // the page that failed here is fetchNextPage's next target, not lost.\n }\n }\n\n return { entries, currentPage };\n },\n\n getNextPageParam: (lastPage) => {\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getBotsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.bots(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/public/bots\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bots: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n refetchOnMount: true,\n staleTime: Infinity,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { ReferralItem } from \"../types/referral\";\n\ntype PageParam = { maxId?: number };\n\nexport function getReferralsInfiniteQueryOptions(username: string) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.accounts.referrals(username),\n initialPageParam: { maxId: undefined } as PageParam,\n queryFn: async ({ pageParam }: { pageParam: PageParam }) => {\n const { maxId } = pageParam ?? {};\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(`/private-api/referrals/${username}`, baseUrl);\n\n if (maxId !== undefined) {\n url.searchParams.set(\"max_id\", maxId.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referrals: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n getNextPageParam: (lastPage: ReferralItem[]) => {\n const nextMaxId = lastPage?.[lastPage.length - 1]?.id;\n return typeof nextMaxId === \"number\" ? ({ maxId: nextMaxId } as PageParam) : undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ReferralStat } from \"../types/referral\";\n\ninterface ReferralStatsResponse {\n total?: number;\n rewarded?: number;\n}\n\nexport function getReferralsStatsQueryOptions(username: string) {\n return queryOptions({\n queryKey: QueryKeys.accounts.referralsStats(username),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/referrals/${username}/stats`,\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch referral stats: ${response.status}`);\n }\n\n const data = await response.json() as ReferralStatsResponse;\n\n if (!data) {\n throw new Error(\"No Referrals for this user!\");\n }\n\n return {\n total: data.total ?? 0,\n rewarded: data.rewarded ?? 0,\n } as ReferralStat;\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendsRow } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FriendsPageParam {\n startFollowing: string;\n}\n\ntype FriendsPage = FriendsRow[];\n\n/**\n * Get list of friends (following/followers) with profile information\n *\n * @param following - The account whose friends to get\n * @param mode - \"following\" or \"followers\"\n * @param followType - Type of follow relationship (default: \"blog\")\n * @param limit - Number of results per page (default: 100)\n * @param enabled - Whether query is enabled (default: true)\n */\nexport function getFriendsInfiniteQueryOptions(\n following: string,\n mode: \"following\" | \"followers\",\n options?: {\n followType?: string;\n limit?: number;\n enabled?: boolean;\n }\n) {\n const { followType = \"blog\", limit = 100, enabled = true } = options ?? {};\n\n return infiniteQueryOptions<\n FriendsPage,\n Error,\n InfiniteData,\n (string | number)[],\n FriendsPageParam\n >({\n queryKey: QueryKeys.accounts.friends(following, mode, followType, limit),\n initialPageParam: { startFollowing: \"\" } as FriendsPageParam,\n enabled,\n refetchOnMount: true,\n\n queryFn: async ({ pageParam }: { pageParam: FriendsPageParam }) => {\n const { startFollowing } = pageParam;\n\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [following, startFollowing === \"\" ? null : startFollowing, followType, limit])) as Follow[];\n\n const accountNames = response.map((e) =>\n mode === \"following\" ? e.following : e.follower\n );\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n const rows: FriendsPage = (accounts ?? []).map((a) => ({\n name: a.name,\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n }));\n\n return rows;\n },\n\n getNextPageParam: (lastPage: FriendsPage): FriendsPageParam | undefined =>\n lastPage && lastPage.length === limit\n ? { startFollowing: lastPage[lastPage.length - 1].name }\n : undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Follow, Profile, FriendSearchResult } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst SEARCH_LIMIT = 30;\n\n/**\n * Search friends (following/followers) by query string\n *\n * @param username - The account whose friends to search\n * @param mode - \"following\" or \"followers\"\n * @param query - Search query string\n */\nexport function getSearchFriendsQueryOptions(\n username: string,\n mode: \"following\" | \"followers\",\n query: string\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.searchFriends(username, mode, query),\n refetchOnMount: false,\n enabled: false, // Manual query via refetch\n queryFn: async (): Promise => {\n if (!query) return [];\n\n const start = query.slice(0, -1);\n const method = mode === \"following\" ? \"get_following\" : \"get_followers\";\n const response = (await callRPC(`condenser_api.${method}`, [username, start, \"blog\", 1000])) as Follow[];\n\n const accountNames = response\n .map((e) => (mode === \"following\" ? e.following : e.follower))\n .filter((name) => name.toLowerCase().includes(query.toLowerCase()))\n .slice(0, SEARCH_LIMIT);\n\n // Get profiles via bridge API\n const accounts = (await callRPC(\"bridge.get_profiles\", {\n accounts: accountNames,\n observer: undefined,\n })) as Profile[];\n\n return (\n accounts?.map((a) => ({\n name: a.name,\n full_name: a.metadata.profile?.name || \"\",\n reputation: a.reputation,\n active: a.active, // Return raw timestamp\n })) ?? []\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsQueryOptions(limit = 20) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTags(),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags\n .filter((x) => x.name !== \"\")\n .filter((x) => !x.name.startsWith(\"hive-\"))\n .map((x) => x.name)\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length > 0\n ? { afterTag: lastPage[lastPage.length - 1] }\n : undefined,\n staleTime: 60 * 60 * 1000, // 1 hour — tags change slowly\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { isCommunity } from \"@/modules/core/utils\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { TrendingTag } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getTrendingTagsWithStatsQueryOptions(limit = 250) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.trendingTagsWithStats(limit),\n queryFn: async ({ pageParam: { afterTag } }) =>\n callRPC(\"condenser_api.get_trending_tags\", [afterTag, limit])\n .then((tags: TrendingTag[]) =>\n tags.filter((tag) => tag.name !== \"\").filter((tag) => !isCommunity(tag.name))\n ),\n initialPageParam: { afterTag: \"\" },\n getNextPageParam: (lastPage) =>\n lastPage?.length ? { afterTag: lastPage[lastPage.length - 1].name } : undefined,\n staleTime: Infinity,\n });\n}\n","import { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\n\nexport function getFragmentsQueryOptions(username: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.fragments(username),\n queryFn: async () => {\n if (!code) {\n return [];\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return response.json() as Promise;\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getFragmentsInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.fragmentsInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/fragments?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch fragments: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { ConfigManager, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\n// TODO: replace any with Entry\nexport function getPromotedPostsQuery(\n type: \"feed\" | \"waves\" = \"feed\"\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.promoted(type),\n queryFn: async () => {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/promoted-entries\", baseUrl);\n if (type === \"waves\") {\n url.searchParams.append(\"short_content\", \"1\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const data = await response.json();\n return data as T[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry, Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getEntryActiveVotesQueryOptions(entry?: Entry) {\n return queryOptions({\n queryKey: QueryKeys.posts.entryActiveVotes(entry?.author, entry?.permlink),\n queryFn: async () => {\n return callRPC(\"condenser_api.get_active_votes\", [\n entry?.author,\n entry?.permlink,\n ]) as Promise;\n },\n enabled: !!entry,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { Vote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a specific user's vote on a post\n * Useful when post has >1000 votes to efficiently get one user's vote\n *\n * @param username - The voter's username\n * @param author - The post author\n * @param permlink - The post permlink\n */\nexport function getUserPostVoteQueryOptions(\n username: string | undefined,\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.userPostVote(username!, author!, permlink!),\n queryFn: async () => {\n const result = await callRPC(\"database_api.list_votes\", {\n start: [username, author, permlink],\n limit: 1,\n order: \"by_voter_comment\"\n });\n\n // Return first vote if found, otherwise null\n return (result?.votes?.[0] || null) as Vote | null;\n },\n enabled: !!username && !!author && !!permlink,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.content(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getContentRepliesQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.contentReplies(author, permlink),\n enabled: !!author && !!permlink,\n queryFn: async (): Promise =>\n callRPC(\"condenser_api.get_content_replies\", {\n author,\n permlink,\n }) as Promise,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostHeaderQueryOptions(author: string, permlink: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.postHeader(author, permlink),\n queryFn: async () => {\n return callRPC(\"bridge.get_post_header\", {\n author,\n permlink,\n }) as Promise;\n },\n initialData: null,\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { Entry } from \"../types\";\n\n/**\n * Filters and censors entries that match DMCA patterns\n * @param entry - Single entry or array of entries to filter\n * @returns Filtered entry/entries with DMCA content censored.\n * Note: Can return null/undefined if input is falsy - callers should guard against this.\n */\nexport function filterDmcaEntry(entry: Entry): Entry | null | undefined;\nexport function filterDmcaEntry(entries: Entry[]): Entry[];\nexport function filterDmcaEntry(entryOrEntries: Entry | Entry[] | null | undefined): Entry | Entry[] | null | undefined {\n if (Array.isArray(entryOrEntries)) {\n // Array elements are non-null Entries, so applyFilter never returns nullish here.\n return entryOrEntries.map((entry) => applyFilter(entry)) as Entry[];\n }\n return applyFilter(entryOrEntries);\n}\n\nfunction applyFilter(entry: Entry | null | undefined): Entry | null | undefined {\n if (!entry) return entry;\n\n const entryPath = `@${entry.author}/${entry.permlink}`;\n const isDmca =\n CONFIG.dmcaPatterns.includes(entryPath) ||\n CONFIG.dmcaPatternRegexes.some((regex) => regex.test(entryPath));\n\n if (isDmca) {\n return {\n ...entry,\n body: \"This post is not available due to a copyright/fraudulent claim.\",\n title: \"\",\n };\n }\n\n return entry;\n}\n","import { callWithQuorum } from \"../../hive-tx\";\nimport { Entry } from \"@/modules/posts/types\";\n\n/**\n * When the primary node returns null for a get_post call,\n * verify by querying multiple random nodes. If any node\n * returns the post, it exists (the first node was lagging).\n *\n * Uses callWithQuorum(quorum=1) which shuffles and queries\n * nodes in batches. Since it shuffles, it's unlikely to hit\n * the same node that just returned null first.\n */\nexport async function verifyPostOnAlternateNode(\n author: string,\n permlink: string,\n observer: string\n): Promise {\n try {\n const response = await callWithQuorum(\"bridge.get_post\", {\n author,\n permlink,\n observer,\n }, 1);\n\n if (\n response &&\n typeof response === \"object\" &&\n (response as Entry).author === author &&\n (response as Entry).permlink === permlink\n ) {\n return response as Entry;\n }\n } catch {\n // All nodes failed or returned null\n }\n\n return null;\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { verifyPostOnAlternateNode } from \"@/modules/bridge/verify-on-alternate-node\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getPostQueryOptions(\n author: string,\n permlink?: string,\n observer = \"\",\n num?: number\n) {\n const cleanPermlink = permlink?.trim();\n const entryPath = `/@${author}/${cleanPermlink ?? \"\"}`;\n\n return queryOptions({\n queryKey: QueryKeys.posts.entry(entryPath),\n queryFn: async () => {\n if (!cleanPermlink || cleanPermlink === \"undefined\") {\n return null;\n }\n\n // hive-tx tries nodes in order; the first healthy node (index 0) handles this call.\n // If it returns null, verifyPostOnAlternateNode skips index 0 and tries others.\n const response = await callRPC(\"bridge.get_post\", {\n author,\n permlink: cleanPermlink,\n observer,\n });\n\n if (!response) {\n // Primary node returned null — verify on alternate nodes\n // to guard against sync lag returning null for valid posts\n const verified = await verifyPostOnAlternateNode(author, cleanPermlink, observer);\n if (!verified) {\n return null;\n }\n const verifiedEntry = num !== undefined ? { ...verified, num } as Entry : verified as Entry;\n return filterDmcaEntry(verifiedEntry);\n }\n\n const entry = num !== undefined ? { ...response, num } as Entry : response as Entry;\n return filterDmcaEntry(entry);\n },\n enabled:\n !!author &&\n !!permlink &&\n permlink.trim() !== \"\" &&\n permlink.trim() !== \"undefined\",\n });\n}\n","import { CONFIG } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { AccountRelationship, Profile } from \"@/modules/accounts/types\";\nimport { Community } from \"@/modules/communities/types/community\";\nimport { Subscription } from \"@/modules/communities/types/subscription\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { filterDmcaEntry } from \"@/modules/posts/utils/filter-dmca-entries\";\n\ntype BridgeParams = Record | unknown[];\n\nexport function bridgeApiCall(endpoint: string, params: BridgeParams, signal?: AbortSignal): Promise {\n return callRPC(`bridge.${endpoint}`, params, undefined, undefined, signal) as Promise;\n}\n\nexport async function resolvePost(\n post: Entry,\n observer: string,\n num?: number,\n signal?: AbortSignal\n): Promise {\n const { json_metadata: json } = post;\n\n if (json?.original_author && json?.original_permlink && json.tags?.[0] === \"cross-post\") {\n try {\n const resp = await getPost(\n json.original_author,\n json.original_permlink,\n observer,\n num,\n signal\n );\n if (resp) {\n return {\n ...post,\n original_entry: resp,\n num,\n };\n }\n return post;\n } catch {\n return post;\n }\n }\n\n return { ...post, num };\n}\n\nasync function resolvePosts(posts: Entry[], observer: string, signal?: AbortSignal): Promise {\n const validatedPosts = posts.map(validateEntry);\n const resolved = await Promise.all(validatedPosts.map((p) => resolvePost(p, observer, undefined, signal)));\n return filterDmcaEntry(resolved) as Entry[];\n}\n\nexport async function getPostsRanked(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_ranked_posts\", {\n sort,\n start_author,\n start_permlink,\n limit,\n tag,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_ranked_posts returned ${typeof resp} instead of an array for sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\nexport async function getAccountPosts(\n sort: string,\n account: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n observer: string = \"\",\n signal?: AbortSignal\n): Promise {\n if (CONFIG.dmcaAccounts.includes(account)) {\n return [];\n }\n\n const resp = await bridgeApiCall(\"get_account_posts\", {\n sort,\n account,\n start_author,\n start_permlink,\n limit,\n observer,\n }, signal);\n\n if (Array.isArray(resp)) {\n return resolvePosts(resp, observer, signal);\n }\n\n if (resp != null) {\n console.warn(\n `[SDK] get_account_posts returned ${typeof resp} instead of an array for account=${account}, sort=${sort}; treating as no results.`\n );\n }\n\n return null;\n}\n\n/**\n * Validates that an Entry object has required properties with non-null values.\n */\nfunction validateEntry(entry: Entry): Entry {\n const newEntry: Entry = {\n ...entry,\n active_votes: Array.isArray(entry.active_votes) ? [...entry.active_votes] : [],\n beneficiaries: Array.isArray(entry.beneficiaries) ? [...entry.beneficiaries] : [],\n blacklists: Array.isArray(entry.blacklists) ? [...entry.blacklists] : [],\n replies: Array.isArray(entry.replies) ? [...entry.replies] : [],\n stats: entry.stats ? { ...entry.stats } : null,\n };\n\n const requiredStringProps: (keyof Entry)[] = [\n \"author\",\n \"title\",\n \"body\",\n \"created\",\n \"category\",\n \"permlink\",\n \"url\",\n \"updated\",\n ];\n\n for (const prop of requiredStringProps) {\n if (newEntry[prop] == null) {\n (newEntry as any)[prop] = \"\";\n }\n }\n\n if (newEntry.author_reputation == null) {\n newEntry.author_reputation = 0;\n }\n if (newEntry.children == null) {\n newEntry.children = 0;\n }\n if (newEntry.depth == null) {\n newEntry.depth = 0;\n }\n if (newEntry.net_rshares == null) {\n newEntry.net_rshares = 0;\n }\n if (newEntry.payout == null) {\n newEntry.payout = 0;\n }\n if (newEntry.percent_hbd == null) {\n newEntry.percent_hbd = 0;\n }\n\n if (!newEntry.stats) {\n newEntry.stats = {\n flag_weight: 0,\n gray: false,\n hide: false,\n total_votes: 0,\n };\n }\n\n if (newEntry.author_payout_value == null) {\n newEntry.author_payout_value = \"0.000 HBD\";\n }\n if (newEntry.curator_payout_value == null) {\n newEntry.curator_payout_value = \"0.000 HBD\";\n }\n if (newEntry.max_accepted_payout == null) {\n newEntry.max_accepted_payout = \"1000000.000 HBD\";\n }\n if (newEntry.payout_at == null) {\n newEntry.payout_at = \"\";\n }\n if (newEntry.pending_payout_value == null) {\n newEntry.pending_payout_value = \"0.000 HBD\";\n }\n if (newEntry.promoted == null) {\n newEntry.promoted = \"0.000 HBD\";\n }\n\n if (newEntry.is_paidout == null) {\n newEntry.is_paidout = false;\n }\n\n return newEntry;\n}\n\nexport async function getPost(\n author: string = \"\",\n permlink: string = \"\",\n observer: string = \"\",\n num?: number,\n signal?: AbortSignal\n): Promise {\n const resp = await bridgeApiCall(\"get_post\", {\n author,\n permlink,\n observer,\n }, signal);\n\n if (resp) {\n const validatedEntry = validateEntry(resp);\n const post = await resolvePost(validatedEntry, observer, num, signal);\n return filterDmcaEntry(post) as Entry;\n }\n\n return undefined;\n}\n\nexport async function getPostHeader(\n author: string = \"\",\n permlink: string = \"\"\n): Promise {\n const resp = await bridgeApiCall(\"get_post_header\", {\n author,\n permlink,\n });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getDiscussion(\n author: string,\n permlink: string,\n observer?: string\n): Promise | null> {\n const resp = await bridgeApiCall | null>(\"get_discussion\", {\n author,\n permlink,\n observer: observer || author,\n });\n\n if (resp) {\n const validatedResp: Record = {};\n for (const [key, entry] of Object.entries(resp)) {\n validatedResp[key] = validateEntry(entry);\n }\n return validatedResp;\n }\n return resp;\n}\n\nexport async function getCommunity(\n name: string,\n observer: string | undefined = \"\"\n): Promise {\n return bridgeApiCall(\"get_community\", { name, observer });\n}\n\nexport async function getCommunities(\n last: string = \"\",\n limit: number = 100,\n query?: string | null,\n sort: string = \"rank\",\n observer: string = \"\"\n): Promise {\n return bridgeApiCall(\"list_communities\", {\n last,\n limit,\n query,\n sort,\n observer,\n });\n}\n\nexport async function normalizePost(post: unknown): Promise {\n const resp = await bridgeApiCall(\"normalize_post\", { post });\n return resp ? validateEntry(resp) : resp;\n}\n\nexport async function getSubscriptions(account: string): Promise {\n return bridgeApiCall(\"list_all_subscriptions\", { account });\n}\n\nexport async function getSubscribers(community: string): Promise {\n return bridgeApiCall(\"list_subscribers\", { community });\n}\n\nexport async function getRelationshipBetweenAccounts(\n follower: string,\n following: string\n): Promise {\n return bridgeApiCall(\"get_relationship_between_accounts\", [\n follower,\n following,\n ]);\n}\n\nexport async function getProfiles(\n accounts: string[],\n observer?: string\n): Promise {\n return bridgeApiCall(\"get_profiles\", { accounts, observer });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getDiscussion } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport enum SortOrder {\n trending = \"trending\",\n author_reputation = \"author_reputation\",\n votes = \"votes\",\n created = \"created\",\n}\n\nfunction parseAsset(value: string): { amount: number; symbol: string } {\n const match = value.match(/^(\\d+\\.?\\d*)\\s*([A-Z]+)$/);\n if (!match) return { amount: 0, symbol: \"\" };\n return {\n amount: parseFloat(match[1]),\n symbol: match[2],\n };\n}\n\nexport function sortDiscussions(\n entry: Entry,\n discussion: Entry[],\n order: SortOrder\n) {\n const allPayout = (c: Entry) =>\n parseAsset(c.pending_payout_value).amount +\n parseAsset(c.author_payout_value).amount +\n parseAsset(c.curator_payout_value).amount;\n\n const absNegative = (a: Entry) => a.net_rshares < 0;\n const isPinned = (a: Entry) =>\n entry.json_metadata?.pinned_reply === `${a.author}/${a.permlink}`;\n\n const sortOrders = {\n trending: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const _a = allPayout(a);\n const _b = allPayout(b);\n if (_a !== _b) {\n return _b - _a;\n }\n\n return 0;\n },\n author_reputation: (a: Entry, b: Entry) => {\n const keyA = a.author_reputation;\n const keyB = b.author_reputation;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n votes: (a: Entry, b: Entry) => {\n const keyA = a.children;\n const keyB = b.children;\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n created: (a: Entry, b: Entry) => {\n if (absNegative(a)) {\n return 1;\n }\n\n if (absNegative(b)) {\n return -1;\n }\n\n const keyA = Date.parse(a.created);\n const keyB = Date.parse(b.created);\n\n if (keyA > keyB) return -1;\n if (keyA < keyB) return 1;\n\n return 0;\n },\n };\n\n const sorted = discussion.sort(sortOrders[order]);\n const pinnedIndex = sorted.findIndex((i) => isPinned(i));\n const pinned = sorted[pinnedIndex];\n if (pinnedIndex >= 0) {\n sorted.splice(pinnedIndex, 1);\n sorted.unshift(pinned);\n }\n return sorted;\n}\n\nexport function getDiscussionsQueryOptions(\n entry: Entry,\n order: SortOrder = SortOrder.created,\n enabled: boolean = true,\n observer?: string\n) {\n // Anonymous readers fall back to CONFIG.defaultObserver rather than the post\n // author. Author-as-observer only helps the minority of authors who curate a\n // mute list; everyone else's comment section came back unfiltered, so the\n // shared moderation account is the better default for logged-out traffic.\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussions(entry?.author, entry?.permlink, order, resolvedObserver),\n queryFn: async () => {\n if (!entry) {\n return [];\n }\n\n const response = await callRPC(\"bridge.get_discussion\", {\n author: entry.author,\n permlink: entry.permlink,\n observer: resolvedObserver,\n });\n\n const results = response\n ? Array.from(Object.values(response as Record))\n : [];\n return filterDmcaEntry(results);\n },\n enabled: enabled && !!entry,\n select: (data: Entry[]) => sortDiscussions(entry, data, order),\n // Preserve optimistic entries during refetch by using structural sharing\n // This ensures newly added comments (is_optimistic: true) aren't wiped out\n // when blockchain hasn't indexed them yet\n structuralSharing: (oldData, newData) => {\n if (!oldData || !newData) return newData;\n\n // Find optimistic entries in old data that aren't in new data yet\n const optimisticEntries = (oldData as Entry[]).filter(\n (entry: Entry) => entry.is_optimistic === true\n );\n\n const fetchedPermlinks = new Set(\n (newData as Entry[]).map((e: Entry) => `${e.author}/${e.permlink}`)\n );\n\n const missingOptimistic = optimisticEntries.filter(\n (opt: Entry) => !fetchedPermlinks.has(`${opt.author}/${opt.permlink}`)\n );\n\n // If there are optimistic entries missing from new data, preserve them\n if (missingOptimistic.length > 0) {\n return [...(newData as Entry[]), ...missingOptimistic];\n }\n\n return newData;\n },\n });\n}\n\nexport function getDiscussionQueryOptions(\n author: string,\n permlink: string,\n observer?: string,\n enabled = true\n) {\n const resolvedObserver = observer || CONFIG.defaultObserver;\n\n return queryOptions({\n queryKey: QueryKeys.posts.discussion(author, permlink, resolvedObserver),\n enabled: enabled && !!author && !!permlink,\n queryFn: async () =>\n getDiscussion(author, permlink, resolvedObserver) as Promise | null>,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getAccountPosts } from \"@/modules/bridge\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n hasNextPage: boolean;\n};\ntype Page = Entry[];\n\nexport function getAccountPostsInfiniteQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return infiniteQueryOptions<\n Page,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.accountPosts(username ?? \"\", filter, limit, observer),\n enabled: !!username && enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n hasNextPage: true,\n } as PageParam,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!pageParam?.hasNextPage || !username) return [];\n\n const response = await getAccountPosts(\n filter,\n username,\n pageParam.author ?? \"\",\n pageParam.permlink ?? \"\",\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n\n getNextPageParam: (lastPage: Page): PageParam | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n // Only consider there's a next page if we got a full page of results\n // A partial page means we've reached the end\n const hasNextPage = (lastPage?.length ?? 0) === limit;\n\n if (!hasNextPage) {\n return undefined;\n }\n\n return {\n author: last?.author,\n permlink: last?.permlink,\n hasNextPage,\n };\n },\n });\n}\n\nexport function getAccountPostsQueryOptions(\n username: string | undefined,\n filter = \"posts\",\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit = 20,\n observer = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.accountPostsPage(username ?? \"\", filter, start_author, start_permlink, limit, observer),\n enabled: !!username && enabled,\n queryFn: async ({ signal } = {} as any) => {\n if (!username) {\n return [];\n }\n\n const response = await getAccountPosts(\n filter,\n username,\n start_author,\n start_permlink,\n limit,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Entry } from \"../types\";\nimport { filterDmcaEntry } from \"../utils/filter-dmca-entries\";\nimport { getPostsRanked } from \"@/modules/bridge\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype PageParam = {\n author: string | undefined;\n permlink: string | undefined;\n};\n\ninterface GetPostsRankedOptions {\n resolvePosts?: boolean;\n}\n\n/**\n * `select` runs on every render, and React Query only reuses its previous\n * result when both the data and the select function are unchanged. These\n * options are rebuilt on each render, so an inline arrow would be a new\n * function every time and every page would be re-sorted on every render.\n * One stable function per sort keeps that memoization working.\n */\nconst displaySelects = new Map<\n string,\n (data: InfiniteData) => InfiniteData\n>();\n\nfunction displaySelect(sort: string) {\n let select = displaySelects.get(sort);\n if (!select) {\n select = (data) => ({\n ...data,\n pages: data.pages.map((page) => orderForDisplay(page, sort)),\n });\n displaySelects.set(sort, select);\n }\n return select;\n}\n\n/**\n * Display order for one page.\n *\n * Pinned entries are captured before the created-date sort: the bridge surfaces\n * them at the head of the response in the community moderators' chosen order,\n * which the sort would scatter by age. Every pin is kept, since an earlier\n * post-sort find() kept one and silently dropped the rest, so multi-pin\n * communities never displayed their other pinned posts. Pins only occur on the\n * first page, cursor pages return none, so this is a no-op elsewhere.\n *\n * Applied in `select` rather than in the query function so it cannot reach the\n * pagination cursor.\n */\nfunction orderForDisplay(page: Entry[], sort: string): Entry[] {\n const pinned = page.filter((entry) => entry.stats?.is_pinned);\n const rest = page.filter((entry) => !entry.stats?.is_pinned);\n\n if (sort === \"hot\") {\n return [...pinned, ...rest];\n }\n\n const byCreated = [...rest].sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n return [...pinned, ...byCreated];\n}\n\nexport function getPostsRankedInfiniteQueryOptions(\n sort: string,\n tag: string,\n limit = 20,\n observer = \"\",\n enabled = true,\n _options: GetPostsRankedOptions = {}\n) {\n return infiniteQueryOptions<\n Entry[],\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.posts.postsRanked(sort, tag, limit, observer),\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await callRPC(\"bridge.get_ranked_posts\", {\n sort,\n start_author: pageParam.author,\n start_permlink: pageParam.permlink,\n limit,\n tag: sanitizedTag,\n observer,\n }, undefined, undefined, signal);\n\n if (response === null || response === undefined) {\n return [];\n }\n\n if (!Array.isArray(response)) {\n throw new Error(\n `[SDK] get_ranked_posts returned ${typeof response} for sort=${sort}`\n );\n }\n\n // Kept in the bridge's own order. getNextPageParam takes the cursor from\n // the last entry of the page this returns, and the bridge continues from\n // that entry in ITS ranking, so reordering here made the next request\n // start from the middle of the previous ranked page: for trending, payout\n // and muted the last entry by date is not the last entry by rank, and\n // scrolling repeated some posts and skipped others. Display order is\n // applied in `select`, which React Query runs after pagination.\n return filterDmcaEntry(response as Entry[]);\n },\n select: displaySelect(sort),\n enabled,\n initialPageParam: {\n author: undefined,\n permlink: undefined,\n } as PageParam,\n getNextPageParam: (lastPage: Entry[]) => {\n // React Query reads \"there is no next page\" from undefined alone, so\n // returning an object here always left it true. An infinite list\n // then keeps calling fetchNextPage at the end of the feed, appending an\n // empty page each time: the query state churns and the cache grows for as\n // long as the reader sits at the bottom.\n const last = lastPage?.[lastPage.length - 1];\n if (!last) {\n return undefined;\n }\n\n return { author: last.author, permlink: last.permlink };\n },\n });\n}\n\nexport function getPostsRankedQueryOptions(\n sort: string,\n start_author: string = \"\",\n start_permlink: string = \"\",\n limit: number = 20,\n tag: string = \"\",\n observer: string = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.postsRankedPage(sort, start_author, start_permlink, limit, tag, observer),\n enabled,\n queryFn: async ({ signal } = {} as any) => {\n let sanitizedTag = tag;\n if (CONFIG.dmcaTagRegexes.some((regex) => regex.test(tag))) {\n sanitizedTag = \"\";\n }\n\n const response = await getPostsRanked(\n sort,\n start_author,\n start_permlink,\n limit,\n sanitizedTag,\n observer,\n signal\n );\n\n return filterDmcaEntry(response ?? []) as Entry[];\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface BlogEntry {\n author: string;\n permlink: string;\n blog: string;\n reblog_on: string;\n reblogged_on: string;\n entry_id: number;\n}\n\nexport interface Reblog {\n author: string;\n permlink: string;\n}\n\nexport function getReblogsQueryOptions(\n username?: string,\n activeUsername?: string,\n limit = 200\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.reblogs(username ?? \"\", limit),\n queryFn: async () => {\n const response = (await callRPC(\"condenser_api.get_blog_entries\", [\n username ?? activeUsername,\n 0,\n limit,\n ])) as BlogEntry[];\n\n return response\n .filter(\n (i) =>\n i.author !== activeUsername &&\n !i.reblogged_on.startsWith(\"1970-\")\n )\n .map((i) => ({ author: i.author, permlink: i.permlink })) as Reblog[];\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get list of usernames who reblogged a specific post\n */\nexport function getRebloggedByQueryOptions(author?: string, permlink?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.rebloggedBy(author ?? \"\", permlink ?? \"\"),\n queryFn: async () => {\n if (!author || !permlink) {\n return [];\n }\n\n const response = (await callRPC(\"condenser_api.get_reblogged_by\", [author, permlink])) as string[];\n\n return Array.isArray(response) ? response : [];\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Schedule } from \"../types/schedule\";\n\nexport function getSchedulesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.schedules(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getSchedulesInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.schedulesInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/schedules?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch schedules: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { Draft } from \"../types/draft\";\n\nexport function getDraftsQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.drafts(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getDraftsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.draftsInfinite(activeUsername, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!activeUsername || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/drafts?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch drafts: ${response.status}`);\n }\n\n const json = await response.json();\n // Normalize response for backwards compatibility\n // If backend doesn't support wrapped format yet, it returns Draft[]\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!activeUsername && !!code,\n });\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, normalizeToWrappedResponse, QueryKeys } from \"@/modules/core\";\nimport { UserImage } from \"../types/user-image\";\n\nasync function fetchUserImages(code: string | undefined): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n return response.json() as Promise;\n}\n\nexport function getImagesQueryOptions(username?: string, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.images(username),\n queryFn: async () => {\n if (!username || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!username && !!code,\n });\n}\n\nexport function getGalleryImagesQueryOptions(activeUsername: string | undefined, code?: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.galleryImages(activeUsername),\n queryFn: async () => {\n if (!activeUsername || !code) {\n return [];\n }\n return fetchUserImages(code);\n },\n enabled: !!activeUsername && !!code,\n });\n}\n\nexport function getImagesInfiniteQueryOptions(\n username: string | undefined,\n code?: string,\n limit: number = 10\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.imagesInfinite(username, limit),\n queryFn: async ({ pageParam = 0 }) => {\n if (!username || !code) {\n return {\n data: [],\n pagination: {\n total: 0,\n limit,\n offset: 0,\n has_next: false,\n },\n };\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/images?format=wrapped&offset=${pageParam}&limit=${limit}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n }),\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch images: ${response.status}`);\n }\n\n const json = await response.json();\n return normalizeToWrappedResponse(json, limit);\n },\n initialPageParam: 0,\n getNextPageParam: (lastPage) => {\n if (lastPage.pagination.has_next) {\n return lastPage.pagination.offset + lastPage.pagination.limit;\n }\n return undefined;\n },\n enabled: !!username && !!code,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nexport function getCommentHistoryQueryOptions(author: string, permlink: string, onlyMeta = false) {\n return queryOptions({\n queryKey: QueryKeys.posts.commentHistory(author, permlink, onlyMeta),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n onlyMeta: onlyMeta ? \"1\" : \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { CommentHistory } from \"../types/comment-history\";\n\nfunction makeEntryPath(author: string, permlink: string): string {\n const cleanAuthor = author?.trim();\n const cleanPermlink = permlink?.trim();\n\n if (!cleanAuthor || !cleanPermlink) {\n throw new Error(\"Invalid entry path: author and permlink are required\");\n }\n\n // Normalize by removing any leading @ or / characters\n const normalizedAuthor = cleanAuthor.replace(/^@+/, \"\");\n const normalizedPermlink = cleanPermlink.replace(/^\\/+/, \"\");\n\n if (!normalizedAuthor || !normalizedPermlink) {\n throw new Error(\"Invalid entry path: author and permlink cannot be empty after normalization\");\n }\n\n return `@${normalizedAuthor}/${normalizedPermlink}`;\n}\n\nexport interface DeletedEntry {\n body: string;\n title: string;\n tags: string[];\n}\n\nexport function getDeletedEntryQueryOptions(author: string, permlink: string) {\n const cleanPermlink = permlink?.trim();\n const cleanAuthor = author?.trim();\n const isValid =\n !!cleanAuthor && !!cleanPermlink && cleanPermlink !== \"undefined\";\n\n const entryPath = isValid ? makeEntryPath(cleanAuthor, cleanPermlink) : \"\";\n\n return queryOptions({\n queryKey: QueryKeys.posts.deletedEntry(entryPath),\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/comment-history\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink: cleanPermlink || \"\",\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch comment history: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n select: (history): DeletedEntry | null => {\n if (!history?.list?.[0]) {\n return null;\n }\n const { body, title, tags } = history.list[0];\n return {\n body,\n title,\n tags,\n };\n },\n enabled: isValid,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { PostTipsResponse } from \"../types/post-tip\";\n\n/**\n * Tips for a single post.\n *\n * Addressed as a GET so the response can be cached. This was a POST, which no\n * cache may store, so the same tip totals were refetched on every mount. The\n * endpoint keys off nothing but author and permlink and needs no auth, and now\n * serves a Cache-Control, so a repeat read can come from the browser instead of\n * the network.\n *\n * `staleTime` is kept at or below the endpoint's own cache window rather than\n * extending it. react-query cannot see how old a response already was when\n * `fetch` served it from the browser cache, so it restarts its window from zero\n * on a body that may already be near expiry; worst-case staleness is the two\n * windows added together.\n */\nexport function getPostTipsQueryOptions(author: string, permlink: string, isEnabled = true) {\n return queryOptions({\n queryKey: QueryKeys.posts.tips(author, permlink),\n queryFn: async () => {\n const path = `/private-api/post-tips/${encodeURIComponent(author)}/${encodeURIComponent(permlink)}`;\n const response = await fetch(CONFIG.privateApiHost + path, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch post tips: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!author && !!permlink && isEnabled,\n staleTime: 60 * 1000,\n });\n}\n","import { Entry, WaveEntry } from \"../types\";\nimport { getDiscussionsQueryOptions, SortOrder } from \"../queries/get-discussions-query-options\";\nimport { CONFIG } from \"@/modules/core\";\n\ntype EntryWithPostId = Entry & { post_id: number };\n\nfunction normalizeContainer(entry: EntryWithPostId, host: string): WaveEntry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds send the publish time as `timestamp`, not `created`.\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n host\n } as WaveEntry;\n}\n\nfunction normalizeParent(entry: EntryWithPostId): Entry {\n return {\n ...entry,\n id: entry.id ?? entry.post_id\n } as Entry;\n}\n\nexport function normalizeWaveEntryFromApi(\n entry:\n | (Entry & { post_id: number; container?: EntryWithPostId | null; parent?: EntryWithPostId | null })\n | null\n | undefined,\n host: string\n): WaveEntry | null {\n if (!entry) {\n return null;\n }\n\n const containerSource = entry.container ?? entry;\n const container = normalizeContainer(containerSource, host);\n\n const parent = entry.parent ? normalizeParent(entry.parent) : undefined;\n\n return {\n ...entry,\n id: entry.id ?? entry.post_id,\n // The private-api waves feeds (following / tag / account) send the publish\n // time as `timestamp`, not `created`; map it so the relative time renders on\n // every card (the For You feed already carries a real `created` from Hive RPC).\n created: entry.created ?? (entry as unknown as { timestamp?: string }).timestamp,\n // The private-api waves feeds omit max_accepted_payout; default it (and the\n // payout strings) to the Hive shape so payout-rendering consumers run their\n // pending+author+curator summation instead of treating the value as missing.\n max_accepted_payout: entry.max_accepted_payout || \"1000000.000 HBD\",\n pending_payout_value: entry.pending_payout_value || \"0.000 HBD\",\n author_payout_value: entry.author_payout_value || \"0.000 HBD\",\n curator_payout_value: entry.curator_payout_value || \"0.000 HBD\",\n host,\n container,\n parent\n } as WaveEntry;\n}\n\nexport function toEntryArray(x: unknown): Entry[] {\n return Array.isArray(x) ? (x as Entry[]) : [];\n}\n\nexport async function getVisibleFirstLevelThreadItems(\n container: WaveEntry\n): Promise {\n const queryOptions = getDiscussionsQueryOptions(container, SortOrder.created, true);\n const discussionItemsRaw = await CONFIG.queryClient.fetchQuery(queryOptions);\n const discussionItems = toEntryArray(discussionItemsRaw);\n\n if (discussionItems.length <= 1) {\n return [];\n }\n\n const firstLevelItems = discussionItems.filter(\n ({ parent_author, parent_permlink }) =>\n parent_author === container.author && parent_permlink === container.permlink\n );\n\n if (firstLevelItems.length === 0) {\n return [];\n }\n\n const visibleItems = firstLevelItems.filter((item) => !item.stats?.gray);\n\n return visibleItems;\n}\n\nexport function mapThreadItemsToWaveEntries(\n items: Entry[],\n container: WaveEntry,\n host: string\n): WaveEntry[] {\n if (items.length === 0) {\n return [];\n }\n\n return items\n .map((item) => {\n const parent = items.find(\n (i) =>\n i.author === item.parent_author &&\n i.permlink === item.parent_permlink &&\n i.author !== host\n );\n\n return {\n ...item,\n id: item.post_id,\n host,\n container,\n parent\n } as WaveEntry;\n })\n .filter((entry) => entry.container.post_id !== entry.post_id)\n .sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n}\n","import { infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\ntype WavesFeedRow = Entry & {\n post_id: number;\n // The wave's container account (e.g. ecency.waves, leothreads), so a mixed\n // cross-container feed can be rendered and acted on per item.\n host?: string;\n // Opaque keyset cursor pointing just past this row.\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type WavesFeedEntry = WaveEntry & { _cursor?: string };\n\nexport interface WavesFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only waves carrying this tag (across all containers). */\n tag?: string;\n /** Only waves from accounts this user follows (across all containers). */\n following?: string;\n /** Only this author's waves (across all containers); the per-author feed. */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedFeedParams {\n containers: string[];\n tag?: string;\n following?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: WavesFeedParams): NormalizedFeedParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n following: params.following?.trim().toLowerCase() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchWavesFeedPage(\n { containers, tag, following, author, observer, limit }: NormalizedFeedParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/feed\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (following) {\n url.searchParams.set(\"following\", following);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves feed: ${response.status}`);\n }\n\n const data = (await response.json()) as WavesFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return { ...entry, _cursor: row._cursor } as WavesFeedEntry;\n })\n .filter((entry): entry is WavesFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container waves feed (the chronological \"For You\" stream, and\n * the Following / Tag feeds via filters).\n *\n * A single esync-backed call returns the newest waves across every indexed\n * container, already merged and time-ordered, with keyset (cursor) pagination,\n * replacing the per-container chain-RPC scan. The optional `tag` / `following`\n * filters narrow the same stream without changing the cursor.\n */\nexport function getWavesFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchWavesFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination. A short page (fewer than `limit` rows) is the\n // end-of-feed signal; on a full page the server always returns the next\n // cursor on the last row. Stopping (rather than looping) is the safe\n // fallback if that cursor were ever absent.\n getNextPageParam: (lastPage: WavesFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n\n/**\n * Page-one of the combined feed as a plain (non-infinite) query under a distinct\n * key, for the \"new waves\" poll. Separate from {@link getWavesFeedQueryOptions}\n * so refreshing it never truncates the infinite feed's loaded pages.\n */\nexport function getWavesLatestFeedQueryOptions(params: WavesFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, following, author, observer, limit } = normalized;\n\n return queryOptions({\n queryKey: [\n ...QueryKeys.posts.wavesFeed({ containers, tag, following, author, observer, limit }),\n \"latest\"\n ],\n staleTime: 0,\n queryFn: ({ signal }) => fetchWavesFeedPage(normalized, undefined, signal)\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\nconst DEFAULT_FEED_LIMIT = 20;\n\n/** The 3Speak video a short embeds, as returned by esync /api/waves/shorts. */\nexport interface ShortVideo {\n platform: string;\n author: string;\n permlink: string;\n embed_url: string;\n thumbnail_url: string | null;\n duration_secs: number | null;\n}\n\ntype ShortsFeedRow = Entry & {\n post_id: number;\n host?: string;\n video?: ShortVideo;\n _cursor?: string;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport type ShortsFeedEntry = WaveEntry & {\n /** The embedded 3Speak video reference for the reels player. */\n video?: ShortVideo;\n _cursor?: string;\n};\n\nexport interface ShortsFeedParams {\n /** Scope to one or more container accounts; omit for the full combined feed. */\n containers?: string[];\n /** Only shorts carrying this tag (across all containers). */\n tag?: string;\n /** Only this author's shorts (across all containers). */\n author?: string;\n /** The viewing user; exclude authors they currently mute. */\n observer?: string;\n /** Page size (default 20). */\n limit?: number;\n}\n\ninterface NormalizedShortsParams {\n containers: string[];\n tag?: string;\n author?: string;\n observer?: string;\n limit: number;\n}\n\nfunction normalizeParams(params: ShortsFeedParams): NormalizedShortsParams {\n return {\n containers: params.containers ?? [],\n tag: params.tag?.trim() || undefined,\n author: params.author?.trim().toLowerCase() || undefined,\n observer: params.observer?.trim().toLowerCase() || undefined,\n limit: params.limit ?? DEFAULT_FEED_LIMIT\n };\n}\n\nasync function fetchShortsFeedPage(\n { containers, tag, author, observer, limit }: NormalizedShortsParams,\n cursor: string | undefined,\n signal?: AbortSignal\n): Promise {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/shorts\", baseUrl);\n url.searchParams.set(\"limit\", String(limit));\n if (cursor) {\n url.searchParams.set(\"cursor\", cursor);\n }\n containers.forEach((container) => url.searchParams.append(\"container\", container));\n if (tag) {\n url.searchParams.set(\"tag\", tag);\n }\n if (author) {\n url.searchParams.set(\"author\", author);\n }\n if (observer) {\n url.searchParams.set(\"observer\", observer);\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch shorts feed: ${response.status}`);\n }\n\n const data = (await response.json()) as ShortsFeedRow[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n return data\n .map((row) => {\n const entry = normalizeWaveEntryFromApi(row, row.host ?? \"\");\n if (!entry) {\n return null;\n }\n return {\n ...entry,\n // A lightweight feed row may omit active_votes; EntryVoteBtn (which uses\n // this entry as React Query initialData) calls .some() on it, so default\n // to an empty array to avoid a crash before the full post query loads.\n active_votes: entry.active_votes ?? [],\n video: row.video,\n _cursor: row._cursor\n } as ShortsFeedEntry;\n })\n .filter((entry): entry is ShortsFeedEntry => Boolean(entry));\n}\n\n/**\n * Combined cross-container shorts (reels) feed: waves that embed a 3Speak video.\n *\n * Backed by esync /api/waves/shorts (via /private-api/waves/shorts). Same shape,\n * keyset pagination and filters as {@link getWavesFeedQueryOptions}, plus a\n * `video` block per item for the vertical reels player. There is no `following`\n * filter in v1.\n */\nexport function getShortsFeedQueryOptions(params: ShortsFeedParams = {}) {\n const normalized = normalizeParams(params);\n const { containers, tag, author, observer, limit } = normalized;\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.shortsFeed({ containers, tag, author, observer, limit }),\n initialPageParam: undefined as string | undefined,\n\n queryFn: ({ pageParam, signal }) => fetchShortsFeedPage(normalized, pageParam, signal),\n\n // Keyset pagination: a short page (fewer than `limit` rows) ends the feed;\n // on a full page the server returns the next cursor on the last row.\n getNextPageParam: (lastPage: ShortsFeedEntry[]) => {\n if (lastPage.length < limit) {\n return undefined;\n }\n return lastPage[lastPage.length - 1]?._cursor;\n }\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport {\n getVisibleFirstLevelThreadItems,\n mapThreadItemsToWaveEntries\n} from \"../utils/waves-helpers\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nconst THREAD_CONTAINER_BATCH_SIZE = 5;\nconst MAX_CONTAINERS_TO_SCAN = 50;\n\ninterface ThreadsResult {\n entries: WaveEntry[];\n}\n\nasync function getThreads(\n host: string,\n pageParam?: WaveEntry\n): Promise {\n let startAuthor = pageParam?.author;\n let startPermlink = pageParam?.permlink;\n let scannedContainers = 0;\n let skipContainerId = pageParam?.post_id;\n\n while (scannedContainers < MAX_CONTAINERS_TO_SCAN) {\n interface AccountPostsParams {\n sort: string;\n account: string;\n limit: number;\n start_author?: string;\n start_permlink?: string;\n }\n\n const rpcParams: AccountPostsParams = {\n sort: \"posts\", // ProfileFilter.posts\n account: host,\n limit: THREAD_CONTAINER_BATCH_SIZE,\n ...(startAuthor ? { start_author: startAuthor } : {}),\n ...(startPermlink ? { start_permlink: startPermlink } : {})\n };\n\n let containers: WaveEntry[];\n try {\n containers = (await callRPC(\"bridge.get_account_posts\", rpcParams)) as WaveEntry[];\n } catch (err) {\n console.error(\"[SDK] getThreads get_account_posts error:\", err);\n return null;\n }\n\n if (!containers || containers.length === 0) {\n return null;\n }\n\n const normalizedContainers = containers.map((container) => {\n container.id = container.post_id;\n container.host = host;\n return container;\n });\n\n for (const container of normalizedContainers) {\n if (skipContainerId && container.post_id === skipContainerId) {\n skipContainerId = undefined;\n continue;\n }\n\n scannedContainers += 1;\n\n if (container.stats?.gray) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n let visibleItems: Entry[];\n try {\n visibleItems = await getVisibleFirstLevelThreadItems(container);\n } catch (err) {\n // A transient bridge.get_discussion failure (RPC timeout, node error, or\n // an oversized response on a large late-day container) must not collapse\n // the whole feed. Treat this container as temporarily unavailable and scan\n // the next one — mirroring the empty-container handling below and the\n // get_account_posts guard above. The query's refetch interval retries it.\n console.error(\"[SDK] getThreads get_discussion error:\", err);\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n if (visibleItems.length === 0) {\n startAuthor = container.author;\n startPermlink = container.permlink;\n continue;\n }\n\n return {\n entries: mapThreadItemsToWaveEntries(visibleItems, container, host)\n };\n }\n\n const lastContainer = normalizedContainers[normalizedContainers.length - 1];\n\n if (!lastContainer) {\n return null;\n }\n\n startAuthor = lastContainer.author;\n startPermlink = lastContainer.permlink;\n }\n\n return null;\n}\n\n// Page = array of WaveEntry; Cursor = WaveEntry (container) or undefined\ntype WavesPage = WaveEntry[];\ntype WavesCursor = WaveEntry | undefined;\n\nexport function getWavesByHostQueryOptions(host: string) {\n return infiniteQueryOptions<\n WavesPage,\n Error,\n InfiniteData,\n string[],\n WavesCursor\n >({\n queryKey: QueryKeys.posts.wavesByHost(host),\n initialPageParam: undefined as WavesCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WavesCursor }) => {\n const result = await getThreads(host, pageParam);\n if (!result) return []; // no items to show for this page\n\n return result.entries;\n },\n\n getNextPageParam: (lastPage: WavesPage): WavesCursor => lastPage?.[0]?.container,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesTagEntryResponse = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nconst DEFAULT_TAG_FEED_LIMIT = 40;\n\nexport function getWavesByTagQueryOptions(host: string, tag: string, limit = DEFAULT_TAG_FEED_LIMIT) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByTag(host, tag),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/tags\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"tag\", tag);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves by tag: ${response.status}`);\n }\n\n const data = await response.json() as WavesTagEntryResponse[];\n\n const result = data\n .slice(0, limit)\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n return result.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves by tag\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ntype WavesFollowingEntry = Entry & {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n};\n\nexport function getWavesFollowingQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesFollowing(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/following\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves following feed: ${response.status}`);\n }\n\n const data = await response.json() as WavesFollowingEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves following feed\", error);\n return [];\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingTag } from \"../types\";\n\ninterface WavesTrendingTagResponse {\n tag: string;\n posts: number;\n}\n\nexport function getWavesTrendingTagsQueryOptions(host?: string, hours = 24) {\n // Omit the container for combined trending tags across all containers.\n const container = host?.trim() || undefined;\n\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingTags(container ?? \"\", hours),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/tags\", baseUrl);\n if (container) {\n url.searchParams.set(\"container\", container);\n }\n url.searchParams.set(\"hours\", hours.toString());\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending tags: ${response.status}`);\n }\n\n const data = await response.json() as WavesTrendingTagResponse[];\n\n return data.map(({ tag, posts }) => ({ tag, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending tags\", error);\n return [];\n }\n }\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { Entry, WaveEntry } from \"../types\";\nimport { normalizeWaveEntryFromApi } from \"../utils/waves-helpers\";\n\ninterface WavesAccountEntry extends Entry {\n post_id: number;\n container?: (Entry & { post_id: number }) | null;\n parent?: (Entry & { post_id: number }) | null;\n}\n\nexport function getWavesByAccountQueryOptions(host: string, username?: string) {\n const normalizedUsername = username?.trim().toLowerCase();\n\n return infiniteQueryOptions({\n queryKey: QueryKeys.posts.wavesByAccount(host, normalizedUsername ?? \"\"),\n enabled: Boolean(normalizedUsername),\n initialPageParam: undefined,\n\n queryFn: async ({ signal }) => {\n if (!normalizedUsername) {\n return [];\n }\n\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/account\", baseUrl);\n url.searchParams.set(\"container\", host);\n url.searchParams.set(\"username\", normalizedUsername);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves for account: ${response.status}`);\n }\n\n const data = await response.json() as WavesAccountEntry[];\n\n if (!Array.isArray(data) || data.length === 0) {\n return [];\n }\n\n const flattened = data\n .map((entry) => normalizeWaveEntryFromApi(entry, host))\n .filter((entry): entry is WaveEntry => Boolean(entry));\n\n if (flattened.length === 0) {\n return [];\n }\n\n return flattened.sort(\n (a, b) => new Date(b.created).getTime() - new Date(a.created).getTime()\n );\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves for account\", error);\n throw error;\n }\n },\n\n getNextPageParam: () => undefined,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConfigManager, QueryKeys } from \"@/modules/core\";\nimport { WaveTrendingAuthor } from \"../types\";\n\nexport function getWavesTrendingAuthorsQueryOptions(host: string) {\n return queryOptions({\n queryKey: QueryKeys.posts.wavesTrendingAuthors(host),\n queryFn: async ({ signal }): Promise => {\n try {\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/waves/trending/authors\", baseUrl);\n url.searchParams.set(\"container\", host);\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch waves trending authors: ${response.status}`);\n }\n\n const data = await response.json() as WaveTrendingAuthor[];\n\n return data.map(({ author, posts }) => ({ author, posts }));\n } catch (error) {\n console.error(\"[SDK] Failed to fetch waves trending authors\", error);\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"../types\";\nimport { normalizePost } from \"@/modules/bridge\";\n\nexport function getNormalizePostQueryOptions(\n post: { author?: string; permlink?: string } | undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.posts.normalize(post?.author ?? \"\", post?.permlink ?? \"\"),\n enabled: enabled && !!post,\n queryFn: async () => normalizePost(post) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core/config\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Entry } from \"@/modules/posts/types\";\nimport { getPostQueryOptions } from \"@/modules/posts/queries\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ninterface VoteOperationDetails {\n voter: string;\n author: string;\n permlink: string;\n weight: number;\n}\n\ninterface AccountVoteHistoryItem {\n timestamp: string;\n op: [string, VoteOperationDetails];\n}\n\ntype AccountVoteHistoryRecord = [number, AccountVoteHistoryItem];\n\ninterface VoteHistoryResult extends VoteOperationDetails {\n num: number;\n timestamp: string;\n}\n\nexport interface VoteHistoryPageParam {\n start: number;\n}\n\nexport interface VoteHistoryPage {\n lastDate: number;\n lastItemFetched: number;\n entries: Entry[];\n}\n\nfunction isEntry(x: unknown): x is Entry {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"author\" in x &&\n \"permlink\" in x &&\n \"active_votes\" in x\n );\n}\n\n/**\n * Calculate days since a date\n */\nfunction getDays(createdDate: string): number {\n const past = new Date(createdDate);\n const now = new Date();\n const diffMs = now.getTime() - past.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n}\n\n/**\n * Get account vote history with entries\n *\n * @param username - Account name to get vote history for\n * @param limit - Number of history items per page (default: 20)\n * @param filters - Additional filters to pass to get_account_history\n * @param dayLimit - Only include votes from last N days (default: 7)\n */\nexport function getAccountVoteHistoryInfiniteQueryOptions(\n username: string,\n options?: {\n limit?: number;\n filters?: F[];\n dayLimit?: number;\n }\n) {\n const { limit = 20, filters = [], dayLimit = 7.0 } = options ?? {};\n\n return infiniteQueryOptions<\n VoteHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n VoteHistoryPageParam\n >({\n queryKey: QueryKeys.accounts.voteHistory(username, limit),\n initialPageParam: { start: -1 },\n\n queryFn: async ({ pageParam }: { pageParam: VoteHistoryPageParam }) => {\n const { start } = pageParam;\n\n const response = (await callRPC(\"condenser_api.get_account_history\", [username, start, limit, ...filters])) as AccountVoteHistoryRecord[];\n\n const mappedResults: VoteHistoryResult[] = response.map(([num, historyObj]) => ({\n ...historyObj.op[1],\n num,\n timestamp: historyObj.timestamp,\n }));\n\n const result = mappedResults.filter(\n (filtered) =>\n filtered.voter === username &&\n filtered.weight !== 0 &&\n getDays(filtered.timestamp) <= dayLimit\n );\n\n const entries: Entry[] = [];\n for (const obj of result) {\n const post = await CONFIG.queryClient.fetchQuery(\n getPostQueryOptions(obj.author, obj.permlink)\n );\n if (isEntry(post)) entries.push(post);\n }\n\n const [firstHistory] = response;\n\n return {\n lastDate: firstHistory ? getDays(firstHistory[1].timestamp) : 0,\n lastItemFetched: firstHistory ? firstHistory[0] : start,\n entries,\n };\n },\n\n getNextPageParam: (lastPage: VoteHistoryPage): VoteHistoryPageParam => ({\n start: lastPage.lastItemFetched,\n }),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Profile } from \"../types\";\nimport { getProfiles } from \"@/modules/bridge\";\n\nexport function getProfilesQueryOptions(\n accounts: string[],\n observer?: string,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.accounts.profiles(accounts, observer ?? \"\"),\n enabled: enabled && accounts.length > 0,\n queryFn: async () => getProfiles(accounts, observer) as Promise,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type {\n BalanceCoinType,\n BalanceHistoryEntry,\n BalanceHistoryResponse,\n} from \"../types\";\n\ninterface BalanceHistoryPage {\n entries: BalanceHistoryEntry[];\n currentPage: number;\n}\n\n/**\n * Cursor for balance history pagination.\n * null = first request (returns the newest page).\n * number = specific page to fetch (decrementing for older data).\n */\ntype BalanceHistoryCursor = number | null;\n\n/**\n * Get balance history for an account with pagination, newest first.\n * Uses the balance-api REST endpoint with direction=desc.\n *\n * Pagination: first call omits `page` to get the newest data.\n * The response includes `total_pages` so we know the current page number.\n * Subsequent calls decrement the page number to load older data.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param pageSize - Number of entries per page\n */\nexport function getBalanceHistoryInfiniteQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n pageSize = 200\n) {\n return infiniteQueryOptions<\n BalanceHistoryPage,\n Error,\n InfiniteData,\n (string | number)[],\n BalanceHistoryCursor\n >({\n queryKey: QueryKeys.wallet.balanceHistory(\n username ?? \"\",\n coinType,\n pageSize\n ),\n initialPageParam: null as BalanceHistoryCursor,\n\n queryFn: async ({ pageParam, signal }) => {\n if (!username) {\n return { entries: [], currentPage: 0 };\n }\n\n const params: Record = {\n \"account-name\": username,\n \"coin-type\": coinType,\n \"page-size\": pageSize,\n direction: \"desc\",\n };\n\n // First call: omit page to get newest data\n // Subsequent calls: pass specific page number\n if (pageParam !== null) {\n params.page = pageParam;\n }\n\n const response = (await callREST(\n \"balance\",\n \"/accounts/{account-name}/balance-history\",\n params,\n undefined,\n undefined,\n signal\n )) as BalanceHistoryResponse;\n\n return {\n entries: response.operations_result,\n currentPage: pageParam ?? response.total_pages,\n };\n },\n\n getNextPageParam: (lastPage) => {\n // Decrement page to go further back in time\n const nextPage = lastPage.currentPage - 1;\n return nextPage >= 1 ? nextPage : undefined;\n },\n\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport type { AggregatedBalanceEntry, BalanceCoinType } from \"../types\";\n\nexport type BalanceAggregationGranularity = \"yearly\" | \"monthly\" | \"daily\";\n\n/**\n * Get aggregated balance history for an account.\n * Uses the balance-api REST endpoint - enables yearly/monthly/daily summary\n * widgets that are impossible via RPC.\n *\n * @param username - Account name\n * @param coinType - HIVE, HBD, or VESTS\n * @param granularity - yearly (default), monthly, or daily\n */\nexport function getAggregatedBalanceQueryOptions(\n username?: string,\n coinType: BalanceCoinType = \"HIVE\",\n granularity: BalanceAggregationGranularity = \"yearly\"\n) {\n return queryOptions({\n queryKey: QueryKeys.wallet.aggregatedHistory(\n username ?? \"\",\n coinType,\n granularity\n ),\n\n queryFn: async () => {\n if (!username) {\n return [];\n }\n\n return (await callREST(\n \"balance\",\n \"/accounts/{account-name}/aggregated-history\",\n {\n \"account-name\": username,\n \"coin-type\": coinType,\n granularity,\n }\n )) as AggregatedBalanceEntry[];\n },\n\n enabled: !!username,\n staleTime: 60_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport interface ProMembersResponse {\n /** Usernames of active Ecency Pro members. */\n members: string[];\n count: number;\n}\n\n/**\n * Public, cached roster of Ecency Pro members. Backed by a lightweight private-api\n * endpoint (no auth) so any surface can decorate a username with a Pro badge without\n * a per-user request.\n *\n * `staleTime` is deliberately shorter than the endpoint's own cache window and is\n * NOT raised to match it. react-query has no idea how old a response already was\n * when `fetch` served it from the browser cache: it treats a nine-minute-old\n * cached body as freshly fetched and starts its own window from zero. Worst-case\n * staleness is therefore the endpoint's window plus this one, so raising this to\n * match the server would roughly double it rather than align it.\n */\nexport function getProMembersQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.accounts.proMembers(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/pro-members\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch pro members: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n staleTime: 5 * 60 * 1000,\n });\n}\n\n/** Lowercased set of member usernames for O(1), case-insensitive membership checks. */\nexport function proMembersSet(members?: string[]): Set {\n return new Set((members ?? []).map((m) => m.toLowerCase()));\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { AccountProfile, FullAccount } from \"../types\";\nimport {\n buildPostingJsonMetadata,\n buildProfileMetadata,\n extractAccountProfile,\n pickRicherMetadataSnapshot,\n} from \"../utils/profile-metadata\";\n\ninterface Payload {\n profile: Partial;\n tokens: AccountProfile[\"tokens\"];\n}\n\n/**\n * React Query mutation hook for updating account profile metadata.\n *\n * This mutation broadcasts an account_update2 operation to update the user's\n * profile information (name, about, location, avatar, cover image, etc.).\n *\n * @param username - The username to update (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Profile Fields:**\n * - name: Display name\n * - about: Bio/description\n * - location: Location\n * - website: Website URL\n * - profile_image: Avatar URL\n * - cover_image: Cover/banner URL\n * - tokens: Social tokens (Twitter, Facebook, etc.)\n * - version: Profile metadata version (auto-set to 2)\n *\n * **Authentication:**\n * - Uses posting authority (account_update2 operation)\n * - Supports all auth methods via platform adapter\n *\n * **Post-Broadcast Actions:**\n * - Optimistically updates account cache with new profile data\n * - Invalidates account cache to refetch from blockchain\n *\n * @example\n * ```typescript\n * const updateProfile = useAccountUpdate(username, {\n * adapter: myAdapter,\n * });\n *\n * // Update profile\n * updateProfile.mutate({\n * profile: {\n * name: \"John Doe\",\n * about: \"Hive enthusiast\",\n * profile_image: \"https://...\",\n * }\n * });\n * ```\n */\nexport function useAccountUpdate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useBroadcastMutation(\n [\"accounts\", \"update\"],\n username,\n (payload: Partial) => {\n // Prefer the freshest cached snapshot. onMutate has just refetched the\n // account from chain, so this usually reflects the current on-chain\n // profile rather than a possibly stale/unloaded render-time value. If\n // the cache instead holds a metadata-poorer row than the render-time\n // snapshot (e.g. a node served a stripped account row), the richer\n // snapshot wins — a partial update must never shrink the profile while\n // any snapshot still knows the full one.\n const account = pickRicherMetadataSnapshot(\n queryClient.getQueryData(\n getAccountFullQueryOptions(username).queryKey\n ),\n data\n );\n\n if (!account) {\n throw new Error(\"[SDK][Accounts] – cannot update not existing account\");\n }\n\n return [\n [\n \"account_update2\",\n {\n account: username!,\n json_metadata: \"\",\n extensions: [] as [],\n // Read-modify-write the FULL on-chain metadata: deep-merge the\n // profile and preserve any non-`profile` top-level keys, so a\n // partial update never wipes unrelated fields.\n posting_json_metadata: buildPostingJsonMetadata({\n existingPostingJsonMetadata: account.posting_json_metadata,\n profile: payload.profile,\n tokens: payload.tokens,\n }),\n },\n ],\n ];\n },\n async (_data: unknown, variables: Partial) => {\n // Optimistic cache update\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n const obj = JSON.parse(JSON.stringify(data)) as FullAccount;\n obj.profile = buildProfileMetadata({\n existingProfile: extractAccountProfile(data),\n profile: variables.profile,\n tokens: variables.tokens,\n });\n\n return obj;\n }\n );\n\n // Invalidate cache to refetch from blockchain\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username)\n ]);\n },\n auth,\n undefined,\n {\n broadcastMode,\n // Before merging, force a fresh on-chain read so a stale or unloaded\n // cached snapshot cannot cause a partial update (e.g. pinning a post,\n // which sets only `pinned`) to overwrite the existing profile with a\n // near-empty object. Best-effort: if the refetch fails, the op builder\n // falls back to the cached snapshot.\n onMutate: async () => {\n if (!username) {\n return;\n }\n try {\n await queryClient.fetchQuery({\n ...getAccountFullQueryOptions(username),\n staleTime: 0,\n });\n } catch {\n // Ignore – fall back to whatever is already cached.\n }\n },\n }\n );\n}\n","import { broadcastJson, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { AuthContext } from \"@/modules/core/types\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getRelationshipBetweenAccountsQueryOptions, getAccountFullQueryOptions } from \"../queries\";\nimport { AccountRelationship } from \"../types\";\n\ntype Kind = \"toggle-ignore\" | \"toggle-follow\";\n\nexport function useAccountRelationsUpdate(\n reference: string | undefined,\n target: string | undefined,\n auth: AuthContext | undefined,\n onSuccess: (data: Partial | undefined) => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"relation\", \"update\", reference, target],\n mutationFn: async (kind: Kind) => {\n const relationsQuery = getRelationshipBetweenAccountsQueryOptions(\n reference!,\n target!\n );\n await getQueryClient().prefetchQuery(relationsQuery);\n const actualRelation = getQueryClient().getQueryData(\n relationsQuery.queryKey\n );\n\n await broadcastJson(\n reference,\n \"follow\",\n [\n \"follow\",\n {\n follower: reference,\n following: target,\n what: [\n ...(kind === \"toggle-ignore\" && !actualRelation?.ignores\n ? [\"ignore\"]\n : []),\n ...(kind === \"toggle-follow\" && !actualRelation?.follows\n ? [\"blog\"]\n : []),\n ],\n },\n ],\n auth\n );\n\n return {\n ...actualRelation,\n ignores:\n kind === \"toggle-ignore\"\n ? !actualRelation?.ignores\n : actualRelation?.ignores,\n follows:\n kind === \"toggle-follow\"\n ? !actualRelation?.follows\n : actualRelation?.follows,\n } satisfies Partial;\n },\n onError,\n onSuccess(data) {\n onSuccess(data);\n\n getQueryClient().setQueryData(\n QueryKeys.accounts.relations(reference!, target!),\n data\n );\n\n // Invalidate account query to refetch follow stats (follower_count, following_count)\n // This is needed because profile pages use staleTime: Infinity for performance\n if (target) {\n getQueryClient().invalidateQueries(\n getAccountFullQueryOptions(target)\n );\n }\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Content Operations\n * Operations for creating, voting, and managing content on Hive blockchain\n */\n\n/**\n * Builds a vote operation.\n * @param voter - Account casting the vote\n * @param author - Author of the post/comment\n * @param permlink - Permlink of the post/comment\n * @param weight - Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote)\n * @returns Vote operation\n */\nexport function buildVoteOp(\n voter: string,\n author: string,\n permlink: string,\n weight: number\n): Operation {\n if (!voter || !author || !permlink) {\n throw new Error(\"[SDK][buildVoteOp] Missing required parameters\");\n }\n if (weight < -10000 || weight > 10000) {\n throw new Error(\"[SDK][buildVoteOp] Weight must be between -10000 and 10000\");\n }\n\n return [\n \"vote\",\n {\n voter,\n author,\n permlink,\n weight,\n },\n ];\n}\n\n/**\n * Builds a comment operation (for posts or replies).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param parentAuthor - Parent author (empty string for top-level posts)\n * @param parentPermlink - Parent permlink (category/tag for top-level posts)\n * @param title - Title of the post (empty for comments)\n * @param body - Content body (required - cannot be empty)\n * @param jsonMetadata - JSON metadata object\n * @returns Comment operation\n */\nexport function buildCommentOp(\n author: string,\n permlink: string,\n parentAuthor: string,\n parentPermlink: string,\n title: string,\n body: string,\n jsonMetadata: Record\n): Operation {\n // Validate all required parameters including body\n if (!author || !permlink || parentPermlink === undefined || !body) {\n throw new Error(\"[SDK][buildCommentOp] Missing required parameters\");\n }\n\n return [\n \"comment\",\n {\n parent_author: parentAuthor,\n parent_permlink: parentPermlink,\n author,\n permlink,\n title,\n body,\n json_metadata: JSON.stringify(jsonMetadata),\n },\n ];\n}\n\n/**\n * Builds a comment options operation (for setting beneficiaries, rewards, etc.).\n * @param author - Author of the comment/post\n * @param permlink - Permlink of the comment/post\n * @param maxAcceptedPayout - Maximum accepted payout (e.g., \"1000000.000 HBD\")\n * @param percentHbd - Percent of payout in HBD (10000 = 100%)\n * @param allowVotes - Allow votes on this content\n * @param allowCurationRewards - Allow curation rewards\n * @param extensions - Extensions array (for beneficiaries, etc.)\n * @returns Comment options operation\n */\nexport function buildCommentOptionsOp(\n author: string,\n permlink: string,\n maxAcceptedPayout: string,\n percentHbd: number,\n allowVotes: boolean,\n allowCurationRewards: boolean,\n extensions: any[]\n): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildCommentOptionsOp] Missing required parameters\");\n }\n\n return [\n \"comment_options\",\n {\n author,\n permlink,\n max_accepted_payout: maxAcceptedPayout,\n percent_hbd: percentHbd,\n allow_votes: allowVotes,\n allow_curation_rewards: allowCurationRewards,\n extensions,\n },\n ];\n}\n\n/**\n * Builds a delete comment operation.\n * @param author - Author of the comment/post to delete\n * @param permlink - Permlink of the comment/post to delete\n * @returns Delete comment operation\n */\nexport function buildDeleteCommentOp(author: string, permlink: string): Operation {\n if (!author || !permlink) {\n throw new Error(\"[SDK][buildDeleteCommentOp] Missing required parameters\");\n }\n\n return [\n \"delete_comment\",\n {\n author,\n permlink,\n },\n ];\n}\n\n/**\n * Builds a reblog operation (custom_json).\n * @param account - Account performing the reblog\n * @param author - Original post author\n * @param permlink - Original post permlink\n * @param deleteReblog - If true, removes the reblog\n * @returns Custom JSON operation for reblog\n */\nexport function buildReblogOp(\n account: string,\n author: string,\n permlink: string,\n deleteReblog: boolean = false\n): Operation {\n if (!account || !author || !permlink) {\n throw new Error(\"[SDK][buildReblogOp] Missing required parameters\");\n }\n\n const json: any = {\n account,\n author,\n permlink,\n };\n\n if (deleteReblog) {\n json.delete = \"delete\";\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\"reblog\", json]),\n required_auths: [],\n required_posting_auths: [account],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Wallet Operations\n * Operations for managing tokens, savings, vesting, and conversions\n */\n\n/**\n * Builds a transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer operation\n */\nexport function buildTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferOp] Missing required parameters\");\n }\n\n return [\n \"transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds multiple transfer operations for multiple recipients.\n * @param from - Sender account\n * @param destinations - Comma or space separated list of recipient accounts\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Array of transfer operations\n */\nexport function buildMultiTransferOps(\n from: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!from || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Create a transfer operation for each destination username\n return destArray.map((dest) =>\n buildTransferOp(from, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds a recurrent transfer operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param recurrence - Recurrence in hours\n * @param executions - Number of executions (2 = executes twice)\n * @returns Recurrent transfer operation\n */\nexport function buildRecurrentTransferOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n recurrence: number,\n executions: number\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Missing required parameters\");\n }\n if (recurrence < 24) {\n throw new Error(\"[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours\");\n }\n\n return [\n \"recurrent_transfer\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n recurrence,\n executions,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a transfer to savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @returns Transfer to savings operation\n */\nexport function buildTransferToSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n },\n ];\n}\n\n/**\n * Builds a transfer from savings operation.\n * @param from - Sender account\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"1.000 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID (use timestamp)\n * @returns Transfer from savings operation\n */\nexport function buildTransferFromSavingsOp(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"transfer_from_savings\",\n {\n from,\n to,\n amount,\n memo: memo || \"\",\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds a cancel transfer from savings operation.\n * @param from - Account that initiated the savings withdrawal\n * @param requestId - Request ID to cancel\n * @returns Cancel transfer from savings operation\n */\nexport function buildCancelTransferFromSavingsOp(\n from: string,\n requestId: number\n): Operation {\n if (!from || requestId === undefined) {\n throw new Error(\"[SDK][buildCancelTransferFromSavingsOp] Missing required parameters\");\n }\n\n return [\n \"cancel_transfer_from_savings\",\n {\n from,\n request_id: requestId,\n },\n ];\n}\n\n/**\n * Builds operations to claim savings interest.\n * Creates a transfer_from_savings and immediately cancels it to claim interest.\n * @param from - Account claiming interest\n * @param to - Receiver account\n * @param amount - Amount with asset symbol (e.g., \"0.001 HIVE\")\n * @param memo - Transfer memo\n * @param requestId - Unique request ID\n * @returns Array of operations [transfer_from_savings, cancel_transfer_from_savings]\n */\nexport function buildClaimInterestOps(\n from: string,\n to: string,\n amount: string,\n memo: string,\n requestId: number\n): Operation[] {\n if (!from || !to || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildClaimInterestOps] Missing required parameters\");\n }\n\n return [\n buildTransferFromSavingsOp(from, to, amount, memo, requestId),\n buildCancelTransferFromSavingsOp(from, requestId),\n ];\n}\n\n/**\n * Builds a transfer to vesting operation (power up).\n * @param from - Account sending HIVE\n * @param to - Account receiving Hive Power\n * @param amount - Amount with HIVE symbol (e.g., \"1.000 HIVE\")\n * @returns Transfer to vesting operation\n */\nexport function buildTransferToVestingOp(\n from: string,\n to: string,\n amount: string\n): Operation {\n if (!from || !to || !amount) {\n throw new Error(\"[SDK][buildTransferToVestingOp] Missing required parameters\");\n }\n\n return [\n \"transfer_to_vesting\",\n {\n from,\n to,\n amount,\n },\n ];\n}\n\n/**\n * Builds a withdraw vesting operation (power down).\n * @param account - Account withdrawing vesting\n * @param vestingShares - Amount of VESTS to withdraw (e.g., \"1.000000 VESTS\")\n * @returns Withdraw vesting operation\n */\nexport function buildWithdrawVestingOp(\n account: string,\n vestingShares: string\n): Operation {\n if (!account || !vestingShares) {\n throw new Error(\"[SDK][buildWithdrawVestingOp] Missing required parameters\");\n }\n\n return [\n \"withdraw_vesting\",\n {\n account,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a delegate vesting shares operation (HP delegation).\n * @param delegator - Account delegating HP\n * @param delegatee - Account receiving HP delegation\n * @param vestingShares - Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\")\n * @returns Delegate vesting shares operation\n */\nexport function buildDelegateVestingSharesOp(\n delegator: string,\n delegatee: string,\n vestingShares: string\n): Operation {\n if (!delegator || !delegatee || !vestingShares) {\n throw new Error(\"[SDK][buildDelegateVestingSharesOp] Missing required parameters\");\n }\n\n return [\n \"delegate_vesting_shares\",\n {\n delegator,\n delegatee,\n vesting_shares: vestingShares,\n },\n ];\n}\n\n/**\n * Builds a set withdraw vesting route operation.\n * @param fromAccount - Account withdrawing vesting\n * @param toAccount - Account receiving withdrawn vesting\n * @param percent - Percentage to route (0-10000, where 10000 = 100%)\n * @param autoVest - Auto convert to vesting\n * @returns Set withdraw vesting route operation\n */\nexport function buildSetWithdrawVestingRouteOp(\n fromAccount: string,\n toAccount: string,\n percent: number,\n autoVest: boolean\n): Operation {\n if (!fromAccount || !toAccount || percent === undefined) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters\");\n }\n if (percent < 0 || percent > 10000) {\n throw new Error(\"[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000\");\n }\n\n return [\n \"set_withdraw_vesting_route\",\n {\n from_account: fromAccount,\n to_account: toAccount,\n percent,\n auto_vest: autoVest,\n },\n ];\n}\n\n/**\n * Builds a convert operation (HBD to HIVE).\n * @param owner - Account converting HBD\n * @param amount - Amount of HBD to convert (e.g., \"1.000 HBD\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Convert operation\n */\nexport function buildConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildConvertOp] Missing required parameters\");\n }\n\n return [\n \"convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a collateralized convert operation (HIVE to HBD via collateral).\n * @param owner - Account converting HIVE\n * @param amount - Amount of HIVE to convert (e.g., \"1.000 HIVE\")\n * @param requestId - Unique request ID (use timestamp)\n * @returns Collateralized convert operation\n */\nexport function buildCollateralizedConvertOp(\n owner: string,\n amount: string,\n requestId: number\n): Operation {\n if (!owner || !amount || requestId === undefined) {\n throw new Error(\"[SDK][buildCollateralizedConvertOp] Missing required parameters\");\n }\n\n return [\n \"collateralized_convert\",\n {\n owner,\n amount,\n requestid: requestId,\n },\n ];\n}\n\n/**\n * Builds a Hive Engine custom_json operation.\n * @param from - Account performing the operation\n * @param contractAction - Engine contract action (e.g., \"transfer\", \"stake\")\n * @param contractPayload - Payload for the contract action\n * @param contractName - Engine contract name (defaults to \"tokens\")\n * @returns Custom JSON operation\n */\nexport function buildEngineOp(\n from: string,\n contractAction: string,\n contractPayload: Record,\n contractName = \"tokens\"\n): Operation {\n return [\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [from],\n required_posting_auths: [],\n json: JSON.stringify({ contractName, contractAction, contractPayload }),\n }];\n}\n\n/**\n * Builds a scot_claim_token operation (posting authority).\n * @param account - Account claiming rewards\n * @param tokens - Array of token symbols to claim\n * @returns Custom JSON operation\n */\nexport function buildEngineClaimOp(\n account: string,\n tokens: string[]\n): Operation {\n return [\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [account],\n json: JSON.stringify(tokens.map((symbol) => ({ symbol }))),\n }];\n}\n\n/**\n * Builds a delegate RC operation (custom_json).\n * @param from - Account delegating RC\n * @param delegatees - Single delegatee or comma-separated list\n * @param maxRc - Maximum RC to delegate (in mana units)\n * @returns Custom JSON operation for RC delegation\n */\nexport function buildDelegateRcOp(\n from: string,\n delegatees: string,\n maxRc: string | number\n): Operation {\n if (!from || !delegatees || maxRc === undefined) {\n throw new Error(\"[SDK][buildDelegateRcOp] Missing required parameters\");\n }\n\n const delegateeArray = delegatees.includes(\",\")\n ? delegatees.split(\",\").map((d) => d.trim())\n : [delegatees];\n\n return [\n \"custom_json\",\n {\n id: \"rc\",\n json: JSON.stringify([\n \"delegate_rc\",\n {\n from,\n delegatees: delegateeArray,\n max_rc: maxRc,\n },\n ]),\n required_auths: [],\n required_posting_auths: [from],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Social Operations\n * Operations for following, muting, and managing social relationships\n */\n\n/**\n * Builds a follow operation (custom_json).\n * @param follower - Account following\n * @param following - Account to follow\n * @returns Custom JSON operation for follow\n */\nexport function buildFollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildFollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"blog\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unfollow operation (custom_json).\n * @param follower - Account unfollowing\n * @param following - Account to unfollow\n * @returns Custom JSON operation for unfollow\n */\nexport function buildUnfollowOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnfollowOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an ignore/mute operation (custom_json).\n * @param follower - Account ignoring\n * @param following - Account to ignore\n * @returns Custom JSON operation for ignore\n */\nexport function buildIgnoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildIgnoreOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"follow\",\n json: JSON.stringify([\n \"follow\",\n {\n follower,\n following,\n what: [\"ignore\"],\n },\n ]),\n required_auths: [],\n required_posting_auths: [follower],\n },\n ];\n}\n\n/**\n * Builds an unignore/unmute operation (custom_json).\n * @param follower - Account unignoring\n * @param following - Account to unignore\n * @returns Custom JSON operation for unignore\n */\nexport function buildUnignoreOp(follower: string, following: string): Operation {\n if (!follower || !following) {\n throw new Error(\"[SDK][buildUnignoreOp] Missing required parameters\");\n }\n\n return buildUnfollowOp(follower, following);\n}\n\n/**\n * Builds a Hive Notify set last read operation (custom_json).\n * @param username - Account setting last read\n * @param date - ISO date string (defaults to now)\n * @returns Array of custom JSON operations for setting last read\n */\nexport function buildSetLastReadOps(username: string, date?: string): Operation[] {\n if (!username) {\n throw new Error(\"[SDK][buildSetLastReadOps] Missing required parameters\");\n }\n\n const lastReadDate = date || new Date().toISOString().split(\".\")[0];\n\n const notifyOp: Operation = [\n \"custom_json\",\n {\n id: \"notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n const ecencyNotifyOp: Operation = [\n \"custom_json\",\n {\n id: \"ecency_notify\",\n json: JSON.stringify([\"setLastRead\", { date: lastReadDate }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n\n return [notifyOp, ecencyNotifyOp];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Governance Operations\n * Operations for witness voting, proposals, and proxy management\n */\n\n/**\n * Builds an account witness vote operation.\n * @param account - Account voting\n * @param witness - Witness account name\n * @param approve - True to approve, false to disapprove\n * @returns Account witness vote operation\n */\nexport function buildWitnessVoteOp(\n account: string,\n witness: string,\n approve: boolean\n): Operation {\n if (!account || !witness || approve === undefined) {\n throw new Error(\"[SDK][buildWitnessVoteOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_vote\",\n {\n account,\n witness,\n approve,\n },\n ];\n}\n\n/**\n * Builds an account witness proxy operation.\n * @param account - Account setting proxy\n * @param proxy - Proxy account name (empty string to remove proxy)\n * @returns Account witness proxy operation\n */\nexport function buildWitnessProxyOp(account: string, proxy: string): Operation {\n if (!account || proxy === undefined) {\n throw new Error(\"[SDK][buildWitnessProxyOp] Missing required parameters\");\n }\n\n return [\n \"account_witness_proxy\",\n {\n account,\n proxy,\n },\n ];\n}\n\n/**\n * Payload for proposal creation\n */\nexport interface ProposalCreatePayload {\n receiver: string;\n subject: string;\n permlink: string;\n start: string;\n end: string;\n dailyPay: string;\n}\n\n/**\n * Builds a create proposal operation.\n * @param creator - Account creating the proposal\n * @param payload - Proposal details (must include start, end, and dailyPay)\n * @returns Create proposal operation\n */\nexport function buildProposalCreateOp(\n creator: string,\n payload: ProposalCreatePayload\n): Operation {\n // Validate required fields including start, end, and dailyPay\n if (\n !creator ||\n !payload.receiver ||\n !payload.subject ||\n !payload.permlink ||\n !payload.start ||\n !payload.end ||\n !payload.dailyPay\n ) {\n throw new Error(\"[SDK][buildProposalCreateOp] Missing required parameters\");\n }\n\n // Validate date format by attempting to parse them\n const startDate = new Date(payload.start);\n const endDate = new Date(payload.end);\n if (startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {\n throw new Error(\n \"[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings\"\n );\n }\n\n return [\n \"create_proposal\",\n {\n creator,\n receiver: payload.receiver,\n start_date: payload.start,\n end_date: payload.end,\n daily_pay: payload.dailyPay,\n subject: payload.subject,\n permlink: payload.permlink,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal votes operation.\n * @param voter - Account voting\n * @param proposalIds - Array of proposal IDs\n * @param approve - True to approve, false to disapprove\n * @returns Update proposal votes operation\n */\nexport function buildProposalVoteOp(\n voter: string,\n proposalIds: number[],\n approve: boolean\n): Operation {\n if (!voter || !proposalIds || proposalIds.length === 0 || approve === undefined) {\n throw new Error(\"[SDK][buildProposalVoteOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal_votes\",\n {\n voter,\n proposal_ids: proposalIds,\n approve,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds a remove proposal operation.\n * @param proposalOwner - Owner of the proposal\n * @param proposalIds - Array of proposal IDs to remove\n * @returns Remove proposal operation\n */\nexport function buildRemoveProposalOp(\n proposalOwner: string,\n proposalIds: number[]\n): Operation {\n if (!proposalOwner || !proposalIds || proposalIds.length === 0) {\n throw new Error(\"[SDK][buildRemoveProposalOp] Missing required parameters\");\n }\n\n return [\n \"remove_proposal\",\n {\n proposal_owner: proposalOwner,\n proposal_ids: proposalIds,\n extensions: [],\n },\n ];\n}\n\n/**\n * Builds an update proposal operation.\n * @param proposalId - Proposal ID to update (must be a valid number, including 0)\n * @param creator - Account that created the proposal\n * @param dailyPay - New daily pay amount\n * @param subject - New subject\n * @param permlink - New permlink\n * @returns Update proposal operation\n */\nexport function buildUpdateProposalOp(\n proposalId: number,\n creator: string,\n dailyPay: string,\n subject: string,\n permlink: string\n): Operation {\n // Validate proposalId properly - check for undefined/null instead of falsy\n // This allows proposalId of 0 which is a valid proposal ID\n if (\n proposalId === undefined ||\n proposalId === null ||\n typeof proposalId !== 'number' ||\n !creator ||\n !dailyPay ||\n !subject ||\n !permlink\n ) {\n throw new Error(\"[SDK][buildUpdateProposalOp] Missing required parameters\");\n }\n\n return [\n \"update_proposal\",\n {\n proposal_id: proposalId,\n creator,\n daily_pay: dailyPay,\n subject,\n permlink,\n extensions: [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Community Operations\n * Operations for managing Hive communities\n */\n\n/**\n * Builds a subscribe to community operation (custom_json).\n * @param username - Account subscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for subscribe\n */\nexport function buildSubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildSubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"subscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds an unsubscribe from community operation (custom_json).\n * @param username - Account unsubscribing\n * @param community - Community name (e.g., \"hive-123456\")\n * @returns Custom JSON operation for unsubscribe\n */\nexport function buildUnsubscribeOp(username: string, community: string): Operation {\n if (!username || !community) {\n throw new Error(\"[SDK][buildUnsubscribeOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"unsubscribe\", { community }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a set user role in community operation (custom_json).\n * @param username - Account setting the role (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to set role for\n * @param role - Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\")\n * @returns Custom JSON operation for setRole\n */\nexport function buildSetRoleOp(\n username: string,\n community: string,\n account: string,\n role: string\n): Operation {\n if (!username || !community || !account || !role) {\n throw new Error(\n `[SDK][buildSetRoleOp] Missing required parameters: username=${username}, community=${community}, account=${account}, role=${role}`\n );\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"setRole\", { community, account, role }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Community properties for update\n */\nexport interface CommunityProps {\n title: string;\n about: string;\n lang: string;\n description: string;\n flag_text: string;\n is_nsfw: boolean;\n}\n\n/**\n * Builds an update community properties operation (custom_json).\n * @param username - Account updating (must be community admin)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param props - Properties to update\n * @returns Custom JSON operation for updateProps\n */\nexport function buildUpdateCommunityOp(\n username: string,\n community: string,\n props: CommunityProps\n): Operation {\n if (!username || !community || !props) {\n throw new Error(\"[SDK][buildUpdateCommunityOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"updateProps\", { community, props }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a pin/unpin post in community operation (custom_json).\n * @param username - Account pinning (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param pin - True to pin, false to unpin\n * @returns Custom JSON operation for pinPost/unpinPost\n */\nexport function buildPinPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n pin: boolean\n): Operation {\n if (!username || !community || !account || !permlink || pin === undefined) {\n throw new Error(\"[SDK][buildPinPostOp] Missing required parameters\");\n }\n\n const action = pin ? \"pinPost\" : \"unpinPost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute post in community operation (custom_json).\n * @param username - Account muting (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for mutePost/unmutePost\n */\nexport function buildMutePostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string,\n mute: boolean\n): Operation {\n if (\n !username ||\n !community ||\n !account ||\n !permlink ||\n mute === undefined\n ) {\n throw new Error(\"[SDK][buildMutePostOp] Missing required parameters\");\n }\n\n const action = mute ? \"mutePost\" : \"unmutePost\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a mute/unmute user in community operation (custom_json).\n * @param username - Account performing mute (must have permission)\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Account to mute/unmute\n * @param notes - Mute reason/notes\n * @param mute - True to mute, false to unmute\n * @returns Custom JSON operation for muteUser/unmuteUser\n */\nexport function buildMuteUserOp(\n username: string,\n community: string,\n account: string,\n notes: string,\n mute: boolean\n): Operation {\n if (!username || !community || !account || mute === undefined) {\n throw new Error(\"[SDK][buildMuteUserOp] Missing required parameters\");\n }\n\n const action = mute ? \"muteUser\" : \"unmuteUser\";\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([action, { community, account, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n\n/**\n * Builds a flag post in community operation (custom_json).\n * @param username - Account flagging\n * @param community - Community name (e.g., \"hive-123456\")\n * @param account - Post author\n * @param permlink - Post permlink\n * @param notes - Flag reason/notes\n * @returns Custom JSON operation for flagPost\n */\nexport function buildFlagPostOp(\n username: string,\n community: string,\n account: string,\n permlink: string,\n notes: string\n): Operation {\n if (!username || !community || !account || !permlink) {\n throw new Error(\"[SDK][buildFlagPostOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"community\",\n json: JSON.stringify([\"flagPost\", { community, account, permlink, notes }]),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Market Operations\n * Operations for trading on the internal Hive market\n */\n\n/**\n * Transaction type for buy/sell operations\n */\nexport enum BuySellTransactionType {\n Buy = \"buy\",\n Sell = \"sell\",\n}\n\n/**\n * Order ID prefix for different order types\n */\nexport enum OrderIdPrefix {\n EMPTY = \"\",\n SWAP = \"9\",\n}\n\n/**\n * Builds a limit order create operation.\n * @param owner - Account creating the order\n * @param amountToSell - Amount and asset to sell\n * @param minToReceive - Minimum amount and asset to receive\n * @param fillOrKill - If true, order must be filled immediately or cancelled\n * @param expiration - Expiration date (ISO string)\n * @param orderId - Unique order ID\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOp(\n owner: string,\n amountToSell: string,\n minToReceive: string,\n fillOrKill: boolean,\n expiration: string,\n orderId: number\n): Operation {\n if (!owner || !amountToSell || !minToReceive || !expiration || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCreateOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_create\",\n {\n owner,\n orderid: orderId,\n amount_to_sell: amountToSell,\n min_to_receive: minToReceive,\n fill_or_kill: fillOrKill,\n expiration,\n },\n ];\n}\n\n/**\n * Helper to format number to 3 decimal places\n */\nfunction formatNumber(value: number, decimals: number = 3): string {\n return value.toFixed(decimals);\n}\n\n/**\n * Builds a limit order create operation with automatic formatting.\n * This is a convenience method that handles buy/sell logic and formatting.\n *\n * For Buy orders: You're buying HIVE with HBD\n * - amountToSell: HBD amount you're spending\n * - minToReceive: HIVE amount you want to receive\n *\n * For Sell orders: You're selling HIVE for HBD\n * - amountToSell: HIVE amount you're selling\n * - minToReceive: HBD amount you want to receive\n *\n * @param owner - Account creating the order\n * @param amountToSell - Amount to sell (number)\n * @param minToReceive - Minimum to receive (number)\n * @param orderType - Buy or Sell\n * @param idPrefix - Order ID prefix\n * @returns Limit order create operation\n */\nexport function buildLimitOrderCreateOpWithType(\n owner: string,\n amountToSell: number,\n minToReceive: number,\n orderType: BuySellTransactionType,\n idPrefix: OrderIdPrefix = OrderIdPrefix.EMPTY\n): Operation {\n // Validate numeric inputs\n if (\n !owner ||\n orderType === undefined ||\n !Number.isFinite(amountToSell) ||\n amountToSell <= 0 ||\n !Number.isFinite(minToReceive) ||\n minToReceive <= 0\n ) {\n throw new Error(\"[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters\");\n }\n\n // Calculate expiration (27 days from now)\n const expiration = new Date(Date.now());\n expiration.setDate(expiration.getDate() + 27);\n const expirationStr = expiration.toISOString().split(\".\")[0];\n\n // Generate order ID\n const orderId = Number(\n `${idPrefix}${Math.floor(Date.now() / 1000)\n .toString()\n .slice(2)}`\n );\n\n // Format amounts based on order type\n // Buy: Sell HBD to buy HIVE\n // Sell: Sell HIVE to buy HBD\n const formattedAmountToSell =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(amountToSell, 3)} HBD`\n : `${formatNumber(amountToSell, 3)} HIVE`;\n\n const formattedMinToReceive =\n orderType === BuySellTransactionType.Buy\n ? `${formatNumber(minToReceive, 3)} HIVE`\n : `${formatNumber(minToReceive, 3)} HBD`;\n\n return buildLimitOrderCreateOp(\n owner,\n formattedAmountToSell,\n formattedMinToReceive,\n false,\n expirationStr,\n orderId\n );\n}\n\n/**\n * Builds a limit order cancel operation.\n * @param owner - Account cancelling the order\n * @param orderId - Order ID to cancel\n * @returns Limit order cancel operation\n */\nexport function buildLimitOrderCancelOp(owner: string, orderId: number): Operation {\n if (!owner || orderId === undefined) {\n throw new Error(\"[SDK][buildLimitOrderCancelOp] Missing required parameters\");\n }\n\n return [\n \"limit_order_cancel\",\n {\n owner,\n orderid: orderId,\n },\n ];\n}\n\n/**\n * Builds a claim reward balance operation.\n * @param account - Account claiming rewards\n * @param rewardHive - HIVE reward to claim (e.g., \"0.000 HIVE\")\n * @param rewardHbd - HBD reward to claim (e.g., \"0.000 HBD\")\n * @param rewardVests - VESTS reward to claim (e.g., \"0.000000 VESTS\")\n * @returns Claim reward balance operation\n */\nexport function buildClaimRewardBalanceOp(\n account: string,\n rewardHive: string,\n rewardHbd: string,\n rewardVests: string\n): Operation {\n if (!account || !rewardHive || !rewardHbd || !rewardVests) {\n throw new Error(\"[SDK][buildClaimRewardBalanceOp] Missing required parameters\");\n }\n\n return [\n \"claim_reward_balance\",\n {\n account,\n reward_hive: rewardHive,\n reward_hbd: rewardHbd,\n reward_vests: rewardVests,\n },\n ];\n}\n","import type { Operation, Authority } from \"../../../hive-tx\";\n\nexport type { Authority };\n\n/**\n * Account Operations\n * Operations for managing accounts, keys, and permissions\n */\n\n/**\n * Builds an account update operation.\n * @param account - Account name\n * @param owner - Owner authority (optional)\n * @param active - Active authority (optional)\n * @param posting - Posting authority (optional)\n * @param memoKey - Memo public key\n * @param jsonMetadata - Account JSON metadata\n * @returns Account update operation\n */\nexport function buildAccountUpdateOp(\n account: string,\n owner: Authority | undefined,\n active: Authority | undefined,\n posting: Authority | undefined,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !memoKey) {\n throw new Error(\"[SDK][buildAccountUpdateOp] Missing required parameters\");\n }\n\n return [\n \"account_update\",\n {\n account,\n owner,\n active,\n posting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an account update2 operation (for posting_json_metadata).\n * @param account - Account name\n * @param jsonMetadata - Account JSON metadata (legacy, usually empty)\n * @param postingJsonMetadata - Posting JSON metadata string\n * @param extensions - Extensions array\n * @returns Account update2 operation\n */\nexport function buildAccountUpdate2Op(\n account: string,\n jsonMetadata: string,\n postingJsonMetadata: string,\n extensions: any[]\n): Operation {\n if (!account || postingJsonMetadata === undefined) {\n throw new Error(\"[SDK][buildAccountUpdate2Op] Missing required parameters\");\n }\n\n return [\n \"account_update2\",\n {\n account,\n json_metadata: jsonMetadata || \"\",\n posting_json_metadata: postingJsonMetadata,\n extensions: (extensions || []) as [],\n },\n ];\n}\n\n/**\n * Public keys for account creation\n */\nexport interface AccountKeys {\n ownerPublicKey: string;\n activePublicKey: string;\n postingPublicKey: string;\n memoPublicKey: string;\n}\n\n/**\n * Builds an account create operation.\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @param fee - Creation fee (e.g., \"3.000 HIVE\")\n * @returns Account create operation\n */\nexport function buildAccountCreateOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys,\n fee: string\n): Operation {\n if (!creator || !newAccountName || !keys || !fee) {\n throw new Error(\"[SDK][buildAccountCreateOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"account_create\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n fee,\n },\n ] satisfies Operation;\n}\n\n/**\n * Builds a create claimed account operation (using account creation tokens).\n * @param creator - Creator account name\n * @param newAccountName - New account name\n * @param keys - Public keys for the new account\n * @returns Create claimed account operation\n */\nexport function buildCreateClaimedAccountOp(\n creator: string,\n newAccountName: string,\n keys: AccountKeys\n): Operation {\n if (!creator || !newAccountName || !keys) {\n throw new Error(\"[SDK][buildCreateClaimedAccountOp] Missing required parameters\");\n }\n\n const owner: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.ownerPublicKey, 1]],\n };\n\n const active: Authority = {\n weight_threshold: 1,\n account_auths: [],\n key_auths: [[keys.activePublicKey, 1]],\n };\n\n const posting: Authority = {\n weight_threshold: 1,\n account_auths: [[\"ecency.app\", 1]],\n key_auths: [[keys.postingPublicKey, 1]],\n };\n\n return [\n \"create_claimed_account\",\n {\n creator,\n new_account_name: newAccountName,\n owner,\n active,\n posting,\n memo_key: keys.memoPublicKey,\n json_metadata: \"\",\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds a claim account operation.\n * @param creator - Account claiming the token\n * @param fee - Fee for claiming (usually \"0.000 HIVE\" for RC-based claims)\n * @returns Claim account operation\n */\nexport function buildClaimAccountOp(creator: string, fee: string): Operation {\n if (!creator || !fee) {\n throw new Error(\"[SDK][buildClaimAccountOp] Missing required parameters\");\n }\n\n return [\n \"claim_account\",\n {\n creator,\n fee,\n extensions: [] as [],\n },\n ];\n}\n\n/**\n * Builds an operation to grant posting permission to another account.\n * Helper that modifies posting authority to add an account.\n * @param account - Account granting permission\n * @param currentPosting - Current posting authority\n * @param grantedAccount - Account to grant permission to\n * @param weightThreshold - Weight threshold of the granted account\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildGrantPostingPermissionOp(\n account: string,\n currentPosting: Authority,\n grantedAccount: string,\n weightThreshold: number,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !grantedAccount || !memoKey) {\n throw new Error(\"[SDK][buildGrantPostingPermissionOp] Missing required parameters\");\n }\n\n // Find existing account or create new entry to prevent duplicates\n const existingIndex = currentPosting.account_auths.findIndex(\n ([acc]) => acc === grantedAccount\n );\n\n const newAccountAuths = [...currentPosting.account_auths];\n if (existingIndex >= 0) {\n // Update existing entry with new weight\n newAccountAuths[existingIndex] = [grantedAccount, weightThreshold];\n } else {\n // Add new entry\n newAccountAuths.push([grantedAccount, weightThreshold]);\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: newAccountAuths,\n };\n\n // Sort account_auths alphabetically for consistency\n newPosting.account_auths.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds an operation to revoke posting permission from an account.\n * Helper that modifies posting authority to remove an account.\n * @param account - Account revoking permission\n * @param currentPosting - Current posting authority\n * @param revokedAccount - Account to revoke permission from\n * @param memoKey - Memo public key (required by Hive blockchain)\n * @param jsonMetadata - Account JSON metadata (required by Hive blockchain)\n * @returns Account update operation with modified posting authority\n */\nexport function buildRevokePostingPermissionOp(\n account: string,\n currentPosting: Authority,\n revokedAccount: string,\n memoKey: string,\n jsonMetadata: string\n): Operation {\n if (!account || !currentPosting || !revokedAccount || !memoKey) {\n throw new Error(\"[SDK][buildRevokePostingPermissionOp] Missing required parameters\");\n }\n\n const newPosting: Authority = {\n ...currentPosting,\n account_auths: currentPosting.account_auths.filter(\n ([acc]) => acc !== revokedAccount\n ),\n };\n\n return [\n \"account_update\",\n {\n account,\n posting: newPosting,\n memo_key: memoKey,\n json_metadata: jsonMetadata,\n },\n ];\n}\n\n/**\n * Builds a change recovery account operation.\n * @param accountToRecover - Account to change recovery account for\n * @param newRecoveryAccount - New recovery account name\n * @param extensions - Extensions array\n * @returns Change recovery account operation\n */\nexport function buildChangeRecoveryAccountOp(\n accountToRecover: string,\n newRecoveryAccount: string,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newRecoveryAccount) {\n throw new Error(\"[SDK][buildChangeRecoveryAccountOp] Missing required parameters\");\n }\n\n return [\n \"change_recovery_account\",\n {\n account_to_recover: accountToRecover,\n new_recovery_account: newRecoveryAccount,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a request account recovery operation.\n * @param recoveryAccount - Recovery account performing the recovery\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param extensions - Extensions array\n * @returns Request account recovery operation\n */\nexport function buildRequestAccountRecoveryOp(\n recoveryAccount: string,\n accountToRecover: string,\n newOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!recoveryAccount || !accountToRecover || !newOwnerAuthority) {\n throw new Error(\"[SDK][buildRequestAccountRecoveryOp] Missing required parameters\");\n }\n\n return [\n \"request_account_recovery\",\n {\n recovery_account: recoveryAccount,\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n\n/**\n * Builds a recover account operation.\n * @param accountToRecover - Account to recover\n * @param newOwnerAuthority - New owner authority\n * @param recentOwnerAuthority - Recent owner authority (for proof)\n * @param extensions - Extensions array\n * @returns Recover account operation\n */\nexport function buildRecoverAccountOp(\n accountToRecover: string,\n newOwnerAuthority: Authority,\n recentOwnerAuthority: Authority,\n extensions: any[] = []\n): Operation {\n if (!accountToRecover || !newOwnerAuthority || !recentOwnerAuthority) {\n throw new Error(\"[SDK][buildRecoverAccountOp] Missing required parameters\");\n }\n\n return [\n \"recover_account\",\n {\n account_to_recover: accountToRecover,\n new_owner_authority: newOwnerAuthority,\n recent_owner_authority: recentOwnerAuthority,\n extensions: extensions as [],\n },\n ];\n}\n","import type { Operation } from \"../../../hive-tx\";\n\n/**\n * Ecency-Specific Operations\n * Custom operations for Ecency platform features (Points, Boost, Promote, etc.)\n */\n\n/**\n * Builds an Ecency Boost Plus subscription operation (custom_json).\n * @param user - User account\n * @param account - Account to subscribe\n * @param duration - Subscription duration in days (must be a valid finite number)\n * @returns Custom JSON operation for boost plus\n */\nexport function buildBoostPlusOp(\n user: string,\n account: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !account || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildBoostPlusOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_boost_plus\",\n json: JSON.stringify({\n user,\n account,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency RC top-up operation (custom_json): a short-term, RC-only\n * delegation to the user's OWN account, paid for with Ecency Points. Distinct\n * from Boost Plus (which delegates Hive Power). The RC amount is fixed\n * server-side, so the user only chooses a duration. Signed with active\n * authority because it spends Points. The actual on-chain `delegate_rc` is\n * broadcast by the Ecency relay account, not here.\n * @param user - User account (payer and recipient of the RC)\n * @param duration - Delegation duration in days (must be a valid finite number)\n * @returns Custom JSON operation for the RC top-up\n */\nexport function buildRcDelegationOp(user: string, duration: number): Operation {\n if (!user || !Number.isInteger(duration) || duration <= 0) {\n throw new Error(\"[SDK][buildRcDelegationOp] Missing or invalid parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_rc_delegation\",\n json: JSON.stringify({\n user,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency promote operation (custom_json).\n * @param user - User account\n * @param author - Post author\n * @param permlink - Post permlink\n * @param duration - Promotion duration in days (must be a valid finite number)\n * @returns Custom JSON operation for promote\n */\nexport function buildPromoteOp(\n user: string,\n author: string,\n permlink: string,\n duration: number\n): Operation {\n // Validate required parameters and ensure duration is a finite number (reject NaN, Infinity)\n if (!user || !author || !permlink || !Number.isFinite(duration)) {\n throw new Error(\"[SDK][buildPromoteOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_promote\",\n json: JSON.stringify({\n user,\n author,\n permlink,\n duration,\n }),\n required_auths: [user],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds an Ecency point transfer operation (custom_json).\n * @param sender - Sender account\n * @param receiver - Receiver account\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Custom JSON operation for point transfer\n */\nexport function buildPointTransferOp(\n sender: string,\n receiver: string,\n amount: string,\n memo: string\n): Operation {\n if (!sender || !receiver || !amount) {\n throw new Error(\"[SDK][buildPointTransferOp] Missing required parameters\");\n }\n\n // Normalize \"POINTS\" to \"POINT\" — backend expects singular form\n const normalizedAmount = amount.replace(/POINTS\\b/, \"POINT\");\n\n return [\n \"custom_json\",\n {\n id: \"ecency_point_transfer\",\n json: JSON.stringify({\n sender,\n receiver,\n amount: normalizedAmount,\n memo: memo || \"\",\n }),\n required_auths: [sender],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds multiple Ecency point transfer operations for multiple recipients.\n * @param sender - Sender account\n * @param destinations - Comma or space separated list of recipients\n * @param amount - Amount to transfer\n * @param memo - Transfer memo\n * @returns Array of custom JSON operations for point transfers\n */\nexport function buildMultiPointTransferOps(\n sender: string,\n destinations: string,\n amount: string,\n memo: string\n): Operation[] {\n if (!sender || !destinations || !amount) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing required parameters\");\n }\n\n // Split the destination input into an array of usernames\n const destArray = destinations\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean);\n\n // Validate parsed destinations\n if (destArray.length === 0) {\n throw new Error(\"[SDK][buildMultiPointTransferOps] Missing valid destinations\");\n }\n\n // Create a point transfer operation for each destination\n return destArray.map((dest) =>\n buildPointTransferOp(sender, dest.trim(), amount, memo)\n );\n}\n\n/**\n * Builds an Ecency community rewards registration operation (custom_json).\n * @param name - Account name to register\n * @returns Custom JSON operation for community registration\n */\nexport function buildCommunityRegistrationOp(name: string): Operation {\n if (!name) {\n throw new Error(\"[SDK][buildCommunityRegistrationOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: \"ecency_registration\",\n json: JSON.stringify({\n name,\n }),\n required_auths: [name],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic active authority custom_json operation.\n * Used for various Ecency operations that require active authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with active authority\n */\nexport function buildActiveCustomJsonOp(\n username: string,\n operationId: string,\n json: Record\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildActiveCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [username],\n required_posting_auths: [],\n },\n ];\n}\n\n/**\n * Builds a generic posting authority custom_json operation.\n * Used for various operations that require posting authority.\n * @param username - Account performing the operation\n * @param operationId - Custom JSON operation ID\n * @param json - JSON payload\n * @returns Custom JSON operation with posting authority\n */\nexport function buildPostingCustomJsonOp(\n username: string,\n operationId: string,\n json: Record | any[]\n): Operation {\n if (!username || !operationId || !json) {\n throw new Error(\"[SDK][buildPostingCustomJsonOp] Missing required parameters\");\n }\n\n return [\n \"custom_json\",\n {\n id: operationId,\n json: JSON.stringify(json),\n required_auths: [],\n required_posting_auths: [username],\n },\n ];\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildFollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for following an account.\n */\nexport interface FollowPayload {\n /** Account to follow */\n following: string;\n}\n\n/**\n * React Query mutation hook for following an account.\n *\n * This mutation broadcasts a follow operation to the Hive blockchain,\n * adding the target account to the follower's \"blog\" follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const followMutation = useFollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Follow an account\n * followMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useFollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"follow\"],\n username,\n ({ following }) => [\n buildFollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnfollowOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unfollowing an account.\n */\nexport interface UnfollowPayload {\n /** Account to unfollow */\n following: string;\n}\n\n/**\n * React Query mutation hook for unfollowing an account.\n *\n * This mutation broadcasts an unfollow operation to the Hive blockchain,\n * removing the target account from the follower's follow list.\n *\n * @param username - The username of the follower (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates relationship cache to show updated follow status\n * - Invalidates account cache to refetch updated follower/following counts\n *\n * @example\n * ```typescript\n * const unfollowMutation = useUnfollow(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unfollow an account\n * unfollowMutation.mutate({\n * following: 'alice'\n * });\n * ```\n */\nexport function useUnfollow(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"unfollow\"],\n username,\n ({ following }) => [\n buildUnfollowOp(username!, following)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.relations(username!, variables.following),\n QueryKeys.accounts.full(variables.following),\n QueryKeys.accounts.followCount(variables.following),\n QueryKeys.accounts.followCount(username!)\n ]);\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ninterface Payload {\n author: string;\n permlink: string;\n}\n\nexport function useBookmarkAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"add\", username],\n mutationFn: async ({ author, permlink }: Payload) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n author,\n permlink,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useBookmarkDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"bookmarks\", \"delete\", username],\n mutationFn: async (bookmarkId: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Bookmarks] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/bookmarks-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n id: bookmarkId,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: () => {\n onSuccess();\n getQueryClient().invalidateQueries({\n queryKey: [\"accounts\", \"bookmarks\", username],\n });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useAccountFavoriteAdd(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"add\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-add\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n return response.json();\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError,\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { useMutation, InfiniteData } from \"@tanstack/react-query\";\nimport { AccountFavorite } from \"../../types\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAccountFavoriteDelete(\n username: string | undefined,\n code: string | undefined,\n onSuccess: () => void,\n onError: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"accounts\", \"favorites\", \"delete\", username],\n mutationFn: async (account: string) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Account][Favorites] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/favorites-delete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n account,\n code,\n }),\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to delete favorite: ${response.status}`);\n }\n return response.json();\n },\n onMutate: async (account: string) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.accounts.favorites(username);\n const infinitePrefix = QueryKeys.accounts.favoritesInfinite(username);\n const checkKey = QueryKeys.accounts.checkFavorite(username, account);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n qc.cancelQueries({ queryKey: checkKey }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((f) => f.account !== account)\n );\n }\n\n const previousCheck = qc.getQueryData(checkKey);\n qc.setQueryData(checkKey, false);\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((f) => f.account !== account),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite, previousCheck };\n },\n onSuccess: (_data, account) => {\n onSuccess();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favorites(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.favoritesInfinite(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.accounts.checkFavorite(username!, account) });\n },\n onError: (err, account, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.accounts.favorites(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n if (context?.previousCheck !== undefined) {\n qc.setQueryData(\n QueryKeys.accounts.checkFavorite(username!, account),\n context.previousCheck\n );\n }\n onError(err);\n },\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\nexport interface Keys {\n owner: PrivateKey;\n active: PrivateKey;\n posting: PrivateKey;\n memo_key: PrivateKey;\n}\n\ninterface Payload {\n keepCurrent?: boolean;\n currentKey: PrivateKey;\n keys: Keys[];\n keysToRevoke?: string[]; // Deprecated: will be treated as revoking from all authorities\n keysToRevokeByAuthority?: Partial>; // Authority-specific revocation\n}\n\nexport function dedupeAndSortKeyAuths(\n existing: Authority[\"key_auths\"],\n additions: [string, number][]\n): Authority[\"key_auths\"] {\n const merged = new Map();\n\n existing.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n additions.forEach(([key, weight]) => {\n merged.set(key.toString(), weight);\n });\n\n return Array.from(merged.entries())\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, weight]) => [key, weight] as [string, number]);\n}\n\ntype UpdateKeyAuthsOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdateKeyAuths(\n username: string,\n options?: UpdateKeyAuthsOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"keys-update\", username],\n mutationFn: async ({\n keys,\n keepCurrent = false,\n currentKey,\n keysToRevoke = [],\n keysToRevokeByAuthority = {}\n }: Payload) => {\n if (keys.length === 0) {\n throw new Error(\n \"[SDK][Update password] – no new keys provided\"\n );\n }\n\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update keys for anon user\"\n );\n }\n\n const prepareAuth = (keyName: keyof Keys) => {\n const auth: Authority = JSON.parse(JSON.stringify(accountData[keyName]));\n\n // Get keys to revoke for this specific authority\n const keysToRevokeForAuthority = keysToRevokeByAuthority[keyName] || [];\n // Fallback to global keysToRevoke for backwards compatibility\n const allKeysToRevoke = [\n ...keysToRevokeForAuthority,\n ...(keysToRevokeByAuthority[keyName] === undefined ? keysToRevoke : [])\n ];\n\n // Filter out keys to revoke from existing keys (authority-specific)\n const existingKeys = keepCurrent\n ? auth.key_auths.filter(([key]) => !allKeysToRevoke.includes(key.toString()))\n : [];\n\n auth.key_auths = dedupeAndSortKeyAuths(\n existingKeys,\n keys.map(\n (values, i) =>\n [values[keyName].createPublic().toString(), i + 1] as [\n string,\n number,\n ]\n )\n );\n\n return auth;\n };\n\n return broadcastOperations(\n [[\"account_update\", {\n account: username,\n json_metadata: accountData.json_metadata,\n owner: prepareAuth(\"owner\"),\n active: prepareAuth(\"active\"),\n posting: prepareAuth(\"posting\"),\n // Always use new memo key when adding new keys\n memo_key: keys[0].memo_key.createPublic().toString(),\n }]],\n currentKey\n );\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { useAccountUpdateKeyAuths } from \"./use-account-update-key-auths\";\n\ninterface Payload {\n newPassword: string;\n currentPassword: string;\n keepCurrent?: boolean;\n}\n\n/**\n * Only native Hive and custom passwords could be updated here\n * Seed based password cannot be updated here, it will be in an account always for now\n */\ntype UpdatePasswordOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountUpdatePassword(\n username: string,\n options?: UpdatePasswordOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);\n\n return useMutation({\n mutationKey: [\"accounts\", \"password-update\", username],\n mutationFn: async ({\n newPassword,\n currentPassword,\n keepCurrent,\n }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Update password] – cannot update password for anon user\"\n );\n }\n const currentKey = PrivateKey.fromLogin(\n username,\n currentPassword,\n \"owner\"\n );\n\n return updateKeys({\n currentKey,\n keepCurrent,\n keys: [\n {\n owner: PrivateKey.fromLogin(username, newPassword, \"owner\"),\n active: PrivateKey.fromLogin(username, newPassword, \"active\"),\n posting: PrivateKey.fromLogin(username, newPassword, \"posting\"),\n memo_key: PrivateKey.fromLogin(username, newPassword, \"memo\"),\n },\n ],\n });\n },\n ...options,\n });\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n useQueryClient,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { FullAccount } from \"../types\";\nimport hs from \"hivesigner\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n}\n\ntype RevokePostingOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountRevokePosting(\n username: string | undefined,\n options: RevokePostingOptions,\n auth?: AuthContextV2\n) {\n const queryClient = useQueryClient();\n\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-posting\", data?.name],\n mutationFn: async ({ accountName, type, key }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot revoke posting for anonymous user\"\n );\n }\n\n const posting = JSON.parse(JSON.stringify(data.posting)) as FullAccount[\"posting\"];\n\n posting.account_auths = posting.account_auths.filter(\n ([account]) => account !== accountName\n );\n\n const operationBody = {\n account: data.name,\n posting,\n memo_key: data.memo_key,\n json_metadata: data.json_metadata,\n };\n\n if (type === \"key\" && key) {\n return broadcastOperations([[\"account_update\", operationBody]], key);\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(\n data.name,\n [[\"account_update\", operationBody]],\n \"active\"\n );\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"account_update\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: (resp, payload, ctx) => {\n (options.onSuccess as\n | ((data: unknown, variables: CommonPayload, context: unknown) => unknown)\n | undefined)?.(resp, payload, ctx);\n queryClient.setQueryData(\n getAccountFullQueryOptions(username).queryKey,\n (data) =>\n ({\n ...data,\n posting: {\n ...data?.posting,\n account_auths:\n data?.posting?.account_auths?.filter(\n ([account]) => account !== payload.accountName\n ) ?? [],\n },\n }) as FullAccount\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { PrivateKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ntype SignType = \"key\" | \"keychain\" | \"hivesigner\" | \"ecency\";\n\ninterface CommonPayload {\n accountName: string;\n type: SignType;\n key?: PrivateKey;\n email?: string;\n}\n\ntype UpdateRecoveryOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n> & {\n hsCallbackUrl?: string;\n};\n\nexport function useAccountUpdateRecovery(\n username: string | undefined,\n code: string | undefined,\n options: UpdateRecoveryOptions,\n auth?: AuthContextV2\n) {\n const { data } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"recovery\", data?.name],\n mutationFn: async ({ accountName, type, key, email }: CommonPayload) => {\n if (!data) {\n throw new Error(\n \"[SDK][Accounts] – cannot change recovery for anonymous user\"\n );\n }\n\n const operationBody = {\n account_to_recover: data.name,\n new_recovery_account: accountName,\n extensions: [] as [],\n };\n\n if (type === \"ecency\") {\n if (!code) {\n throw new Error(\"[SDK][Accounts] – missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/recoveries-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n code,\n email,\n publicKeys: [\n ...data.owner.key_auths,\n ...data.active.key_auths,\n ...data.posting.key_auths,\n data.memo_key,\n ],\n }),\n });\n\n // Raw fetch resolves on 4xx/5xx, so guard explicitly — otherwise the\n // caller's onSuccess shows a \"recovery updated\" toast on a failed request.\n // (The missing Content-Type header also made the backend skip JSON parsing.)\n if (!response.ok) {\n throw new Error(`[SDK][Accounts] Failed to add recovery: ${response.status}`);\n }\n\n return response;\n } else if (type === \"key\" && key) {\n return broadcastOperations(\n [[\"change_recovery_account\", operationBody]],\n key\n );\n } else if (type === \"keychain\") {\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Accounts] – missing keychain broadcaster\");\n }\n return auth.adapter.broadcastWithKeychain(data.name, [[\"change_recovery_account\", operationBody]], \"owner\");\n } else {\n if (!options.hsCallbackUrl && process.env.NODE_ENV === \"development\") {\n console.warn(\"[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing.\");\n }\n return hs.sendOperation(\n [\"change_recovery_account\", operationBody],\n options.hsCallbackUrl ? { callback: options.hsCallbackUrl } : {},\n () => {}\n );\n }\n },\n onError: options.onError,\n onSuccess: options.onSuccess,\n });\n}\n","import { PublicKey } from \"../../../hive-tx\";\nimport type { Authority } from \"../../../hive-tx\";\nimport { FullAccount } from \"../types\";\n\n/**\n * Check whether an authority would still meet its weight_threshold\n * after removing the given keys. This prevents revoking keys that\n * would leave an authority unable to sign (especially for multisig).\n */\nexport function canRevokeFromAuthority(\n auth: Authority,\n revokingKeyStrs: Set\n): boolean {\n const remainingWeight = auth.key_auths\n .filter(([key]) => !revokingKeyStrs.has(String(key)))\n .reduce((sum, [, weight]) => sum + weight, 0);\n\n // account_auths also contribute weight\n const accountWeight = (auth.account_auths ?? []).reduce(\n (sum: number, [, weight]: [string, number]) => sum + weight,\n 0\n );\n\n return (remainingWeight + accountWeight) >= auth.weight_threshold;\n}\n\n/**\n * Build an account_update operation that removes the given public keys\n * from the relevant authorities.\n *\n * Only includes the `owner` field when a revoking key actually exists\n * in the owner authority - omitting it allows active-level signing.\n *\n * Returns the operation payload (without the \"account_update\" tag) so\n * callers can wrap it as needed for their broadcast method.\n */\nexport function buildRevokeKeysOp(\n accountData: FullAccount,\n revokingKeys: PublicKey[]\n) {\n const revokingKeyStrs = new Set(revokingKeys.map((k) => k.toString()));\n\n const hasAnyKeyInAuth = (auth: Authority) =>\n auth.key_auths.some(\n ([key]: [string | PublicKey, number]) => revokingKeyStrs.has(String(key))\n );\n\n const prepareAuth = (auth: Authority): Authority => {\n const clone: Authority = JSON.parse(JSON.stringify(auth));\n clone.key_auths = clone.key_auths.filter(\n ([key]) => !revokingKeyStrs.has(key.toString())\n );\n return clone;\n };\n\n const needsOwnerUpdate = hasAnyKeyInAuth(accountData.owner);\n\n return {\n account: accountData.name,\n json_metadata: accountData.json_metadata,\n owner: needsOwnerUpdate ? prepareAuth(accountData.owner) : undefined,\n active: prepareAuth(accountData.active),\n posting: prepareAuth(accountData.posting),\n memo_key: accountData.memo_key\n };\n}\n","import { PrivateKey, PublicKey } from \"../../../hive-tx\";\nimport {\n useMutation,\n useQuery,\n type UseMutationOptions,\n} from \"@tanstack/react-query\";\nimport { getAccountFullQueryOptions } from \"../queries\";\nimport { buildRevokeKeysOp } from \"./build-revoke-keys-op\";\nimport { broadcastOperations } from \"@/modules/core/hive-tx\";\n\ninterface Payload {\n currentKey: PrivateKey;\n /** Keys to revoke. Accepts a single key or an array. */\n revokingKey: PublicKey | PublicKey[];\n}\n\n/**\n * Revoke one or more keys from an account on the Hive blockchain.\n *\n * When revoking keys that exist only in active/posting authorities,\n * the owner field is omitted from the operation so active-level\n * signing is sufficient.\n */\ntype RevokeKeyOptions = Pick<\n UseMutationOptions,\n \"onSuccess\" | \"onError\"\n>;\n\nexport function useAccountRevokeKey(\n username: string | undefined,\n options?: RevokeKeyOptions\n) {\n const { data: accountData } = useQuery(getAccountFullQueryOptions(username));\n\n return useMutation({\n mutationKey: [\"accounts\", \"revoke-key\", accountData?.name],\n mutationFn: async ({ currentKey, revokingKey }: Payload) => {\n if (!accountData) {\n throw new Error(\n \"[SDK][Revoke key] – cannot update keys for anon user\"\n );\n }\n\n const revokingKeys = Array.isArray(revokingKey) ? revokingKey : [revokingKey];\n const op = buildRevokeKeysOp(accountData, revokingKeys);\n\n return broadcastOperations([[\"account_update\", op]], currentKey);\n },\n ...options,\n });\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildClaimAccountOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for claiming account creation tokens.\n */\nexport interface ClaimAccountPayload {\n /** Creator account claiming the token */\n creator: string;\n /** Fee for claiming (usually \"0.000 HIVE\" for RC-based claims) */\n fee?: string;\n}\n\n/**\n * React Query mutation hook for claiming account creation tokens.\n *\n * This mutation broadcasts a claim_account operation to claim an account\n * creation token using Resource Credits (RC). The claimed token can later\n * be used to create a new account for free using the create_claimed_account\n * operation.\n *\n * @param username - The username claiming the account token (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account cache to update pending_claimed_accounts count\n * - Updates account query data to set pending_claimed_accounts = 0 optimistically\n *\n * **Operation Details:**\n * - Uses native claim_account operation\n * - Fee: \"0.000 HIVE\" (uses RC instead of HIVE)\n * - Authority: Active key (required for claiming)\n *\n * **RC Requirements:**\n * - Requires sufficient Resource Credits (RC)\n * - RC amount varies based on network conditions\n * - Claiming without sufficient RC will fail\n *\n * **Use Case:**\n * - Claim tokens in advance when RC is available\n * - Create accounts later without paying HIVE fee\n * - Useful for onboarding services and apps\n *\n * @example\n * ```typescript\n * const claimMutation = useClaimAccount(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Claim account token using RC\n * claimMutation.mutate({\n * creator: 'alice',\n * fee: '0.000 HIVE'\n * });\n * ```\n */\nexport function useClaimAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"claimAccount\"],\n username,\n ({ creator, fee = \"0.000 HIVE\" }) => [\n buildClaimAccountOp(creator, fee)\n ],\n async (_result: any, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(variables.creator),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildGrantPostingPermissionOp, type Authority } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface GrantPostingPermissionPayload {\n currentPosting: Authority;\n grantedAccount: string;\n weightThreshold: number;\n memoKey: string;\n jsonMetadata: string;\n}\n\nexport function useGrantPostingPermission(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"grant-posting-permission\"],\n username,\n (payload) => [\n buildGrantPostingPermissionOp(\n username!,\n payload.currentPosting,\n payload.grantedAccount,\n payload.weightThreshold,\n payload.memoKey,\n payload.jsonMetadata\n )\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildAccountCreateOp, buildCreateClaimedAccountOp, type AccountKeys } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface CreateAccountPayload {\n newAccountName: string;\n keys: AccountKeys;\n fee: string;\n /** If true, uses a claimed account token instead of paying the fee */\n useClaimed?: boolean;\n}\n\nexport function useCreateAccount(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"accounts\", \"create\"],\n username,\n (payload) => [\n payload.useClaimed\n ? buildCreateClaimedAccountOp(username!, payload.newAccountName, payload.keys)\n : buildAccountCreateOp(username!, payload.newAccountName, payload.keys, payload.fee)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { parseAsset } from \"@/modules/core/utils\";\nimport { DynamicProps } from \"@/modules/core/types\";\nimport { FullAccount } from \"../types\";\nimport { calculateVPMana, calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\n\nconst HIVE_VOTING_MANA_REGENERATION_SECONDS = 5 * 60 * 60 * 24; // 5 days\nconst HIVE_100_PERCENT = 10000;\nconst HIVE_VOTE_DUST_THRESHOLD = 50_000_000;\n\nfunction getEffectiveVests(account: FullAccount): number {\n const vesting = parseAsset(account.vesting_shares).amount;\n const received = parseAsset(account.received_vesting_shares).amount;\n const delegated = parseAsset(account.delegated_vesting_shares).amount;\n const withdrawRate = parseAsset(account.vesting_withdraw_rate).amount;\n const alreadyWithdrawn =\n (Number(account.to_withdraw) - Number(account.withdrawn)) / 1e6;\n const withdrawVests = Math.min(withdrawRate, alreadyWithdrawn);\n\n return vesting + received - delegated - withdrawVests;\n}\n\nfunction vestsToRshares(vests: number, votingPowerValue: number, votePerc: number): number {\n const vestingShares = vests * 1e6;\n const power = (votingPowerValue * votePerc) / 1e4 / 50 + 1;\n return (power * vestingShares) / 1e4;\n}\n\nfunction hasStableVoteHardfork(dynamicProps: DynamicProps): boolean {\n if (Number.isFinite(dynamicProps.lastHardfork)) {\n return dynamicProps.lastHardfork >= 28;\n }\n\n const [major = \"0\", minor = \"0\"] = (dynamicProps.currentHardforkVersion ?? \"0.0.0\").split(\".\");\n return Number(major) > 1 || (Number(major) === 1 && Number(minor) >= 28);\n}\n\nfunction stableVoteRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n weight: number\n): number {\n const reserveRate =\n dynamicProps.votePowerReserveRate ||\n Number(dynamicProps.raw?.globalDynamic?.vote_power_reserve_rate ?? 0);\n\n if (!Number.isFinite(reserveRate) || reserveRate <= 0) {\n return 0;\n }\n\n const effectiveVests = getEffectiveVests(account);\n if (!Number.isFinite(effectiveVests) || effectiveVests <= 0) {\n return 0;\n }\n\n const vestingShares = effectiveVests * 1e6;\n const usedMana =\n Math.ceil(\n (vestingShares * weight * 60 * 60 * 24) /\n HIVE_100_PERCENT /\n (reserveRate * HIVE_VOTING_MANA_REGENERATION_SECONDS)\n );\n\n const mana = calculateVPMana(account);\n const currentMana = Math.min(mana.current_mana, mana.max_mana);\n\n if (!Number.isFinite(currentMana) || usedMana > currentMana) {\n return 0;\n }\n\n return Math.max(usedMana - HIVE_VOTE_DUST_THRESHOLD, 0);\n}\n\nexport function votingRshares(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n\n if (hasStableVoteHardfork(dynamicProps)) {\n return stableVoteRshares(account, dynamicProps, weight);\n }\n\n let totalVests = 0;\n try {\n totalVests = getEffectiveVests(account);\n if (!Number.isFinite(totalVests)) {\n return 0;\n }\n } catch {\n return 0;\n }\n\n return vestsToRshares(totalVests, votingPowerValue, weight);\n}\n\nexport function votingPower(account: FullAccount): number {\n const calc = calculateVPMana(account);\n return calc.percentage / 100;\n}\n\nexport function powerRechargeTime(power: number) {\n if (!Number.isFinite(power)) {\n throw new TypeError(\"Voting power must be a finite number\");\n }\n if (power < 0 || power > 100) {\n throw new RangeError(\"Voting power must be between 0 and 100\");\n }\n const missingPower = 100 - power;\n return (\n (missingPower * 100 * HIVE_VOTING_MANA_REGENERATION_SECONDS) / 10000\n );\n}\n\nexport function downVotingPower(account: FullAccount): number {\n const totalShares =\n parseFloat(account.vesting_shares) +\n parseFloat(account.received_vesting_shares) -\n parseFloat(account.delegated_vesting_shares);\n const elapsed = Math.floor(Date.now() / 1000) - account.downvote_manabar.last_update_time;\n const maxMana = (totalShares * 1000000) / 4;\n\n if (maxMana <= 0) {\n return 0;\n }\n\n let currentMana =\n parseFloat(account.downvote_manabar.current_mana.toString()) +\n (elapsed * maxMana) / HIVE_VOTING_MANA_REGENERATION_SECONDS;\n\n if (currentMana > maxMana) {\n currentMana = maxMana;\n }\n const currentManaPerc = (currentMana * 100) / maxMana;\n\n if (isNaN(currentManaPerc)) {\n return 0;\n }\n\n if (currentManaPerc > 100) {\n return 100;\n }\n return currentManaPerc;\n}\n\nexport function rcPower(account: RCAccount): number {\n const calc = calculateRCMana(account);\n return calc.percentage / 100;\n}\n\nexport function votingValue(\n account: FullAccount,\n dynamicProps: DynamicProps,\n votingPowerValue: number,\n weight: number = 10000\n): number {\n if (!Number.isFinite(votingPowerValue) || !Number.isFinite(weight)) {\n return 0;\n }\n const { fundRecentClaims, fundRewardBalance, base, quote } = dynamicProps;\n\n if (\n !Number.isFinite(fundRecentClaims) ||\n !Number.isFinite(fundRewardBalance) ||\n !Number.isFinite(base) ||\n !Number.isFinite(quote)\n ) {\n return 0;\n }\n\n if (fundRecentClaims === 0 || quote === 0) {\n return 0;\n }\n\n const rShares = votingRshares(account, dynamicProps, votingPowerValue, weight);\n\n if (!Number.isFinite(rShares)) {\n return 0;\n }\n\n return (rShares / fundRecentClaims) * fundRewardBalance * (base / quote);\n}\n","import type { Operation } from \"../../hive-tx\";\n\n/**\n * Authority levels for Hive blockchain operations.\n * - posting: Social operations (voting, commenting, reblogging)\n * - active: Financial and account management operations\n * - owner: Critical security operations (key changes, account recovery)\n * - memo: Memo encryption/decryption (rarely used for signing)\n */\nexport type AuthorityLevel = 'posting' | 'active' | 'owner' | 'memo';\n\n/**\n * Maps operation types to their required authority level.\n *\n * This mapping is used to determine which key is needed to sign a transaction,\n * enabling smart auth fallback and auth upgrade UI.\n *\n * @remarks\n * - Most social operations (vote, comment, reblog) require posting authority\n * - Financial operations (transfer, withdraw) require active authority\n * - Account management operations require active authority\n * - Security operations (password change, account recovery) require owner authority\n * - custom_json requires dynamic detection based on required_auths vs required_posting_auths\n */\nexport const OPERATION_AUTHORITY_MAP: Record = {\n // Posting authority operations\n vote: 'posting',\n comment: 'posting',\n delete_comment: 'posting',\n comment_options: 'posting',\n claim_reward_balance: 'posting',\n\n // Active authority operations - Financial\n cancel_transfer_from_savings: 'active',\n collateralized_convert: 'active',\n convert: 'active',\n delegate_vesting_shares: 'active',\n recurrent_transfer: 'active',\n set_withdraw_vesting_route: 'active',\n transfer: 'active',\n transfer_from_savings: 'active',\n transfer_to_savings: 'active',\n transfer_to_vesting: 'active',\n withdraw_vesting: 'active',\n\n // Active authority operations - Market\n limit_order_create: 'active',\n limit_order_cancel: 'active',\n\n // Active authority operations - Account Management\n account_update: 'active',\n account_update2: 'active',\n claim_account: 'active',\n create_claimed_account: 'active',\n\n // Active authority operations - Governance\n account_witness_proxy: 'active',\n account_witness_vote: 'active',\n remove_proposal: 'active',\n update_proposal_votes: 'active',\n\n // Owner authority operations - Security & Account Recovery\n change_recovery_account: 'owner',\n request_account_recovery: 'owner',\n recover_account: 'owner',\n reset_account: 'owner',\n set_reset_account: 'owner',\n\n // Note: Some operations are handled separately via content inspection:\n // - custom_json: via getCustomJsonAuthority() - posting or active based on required_auths\n // - create_proposal/update_proposal: via getProposalAuthority() - typically active\n};\n\n/**\n * Determines authority required for a custom_json operation.\n *\n * Custom JSON operations can require either posting or active authority\n * depending on which field is populated:\n * - required_auths (active authority)\n * - required_posting_auths (posting authority)\n *\n * @param customJsonOp - The custom_json operation to inspect\n * @returns 'active' if requires active authority, 'posting' if requires posting authority\n *\n * @example\n * ```typescript\n * // Reblog operation (posting authority)\n * const reblogOp: Operation = ['custom_json', {\n * required_auths: [],\n * required_posting_auths: ['alice'],\n * id: 'reblog',\n * json: '...'\n * }];\n * getCustomJsonAuthority(reblogOp); // Returns 'posting'\n *\n * // Some active authority custom_json\n * const activeOp: Operation = ['custom_json', {\n * required_auths: ['alice'],\n * required_posting_auths: [],\n * id: 'some_active_op',\n * json: '...'\n * }];\n * getCustomJsonAuthority(activeOp); // Returns 'active'\n * ```\n */\nexport function getCustomJsonAuthority(customJsonOp: Operation): AuthorityLevel {\n const opType = customJsonOp[0];\n const payload = customJsonOp[1];\n\n if (opType !== 'custom_json') {\n throw new Error('Operation is not a custom_json operation');\n }\n\n // Type assertion for custom_json payload\n const customJson = payload as {\n required_auths?: string[];\n required_posting_auths?: string[];\n id: string;\n json: string;\n };\n\n // If required_auths is set and non-empty, needs active authority\n if (customJson.required_auths && customJson.required_auths.length > 0) {\n return 'active';\n }\n\n // If only required_posting_auths is set, needs posting authority\n if (customJson.required_posting_auths && customJson.required_posting_auths.length > 0) {\n return 'posting';\n }\n\n // Default to posting for custom_json (most common case)\n return 'posting';\n}\n\n/**\n * Determines authority required for a proposal operation.\n *\n * Proposal operations (create_proposal, update_proposal) typically require\n * active authority as they involve financial commitments and funding allocations.\n *\n * @param proposalOp - The proposal operation to inspect\n * @returns 'active' authority requirement\n *\n * @remarks\n * Unlike custom_json, proposal operations don't have explicit required_auths fields.\n * They always use the creator's authority, which defaults to active for financial\n * operations involving the DAO treasury.\n *\n * @example\n * ```typescript\n * const proposalOp: Operation = ['create_proposal', {\n * creator: 'alice',\n * receiver: 'bob',\n * subject: 'My Proposal',\n * permlink: 'my-proposal',\n * start: '2026-03-01T00:00:00',\n * end: '2026-04-01T00:00:00',\n * daily_pay: '100.000 HBD',\n * extensions: []\n * }];\n * getProposalAuthority(proposalOp); // Returns 'active'\n * ```\n */\nexport function getProposalAuthority(proposalOp: Operation): AuthorityLevel {\n const opType = proposalOp[0];\n\n if (opType !== 'create_proposal' && opType !== 'update_proposal') {\n throw new Error('Operation is not a proposal operation');\n }\n\n // Proposal operations require active authority for financial operations\n return 'active';\n}\n\n/**\n * Determines the required authority level for any operation.\n *\n * Uses the OPERATION_AUTHORITY_MAP for standard operations, and dynamic\n * detection for custom_json operations.\n *\n * @param op - The operation to check\n * @returns 'posting' or 'active' authority requirement\n *\n * @example\n * ```typescript\n * const voteOp: Operation = ['vote', { voter: 'alice', author: 'bob', permlink: 'post', weight: 10000 }];\n * getOperationAuthority(voteOp); // Returns 'posting'\n *\n * const transferOp: Operation = ['transfer', { from: 'alice', to: 'bob', amount: '1.000 HIVE', memo: '' }];\n * getOperationAuthority(transferOp); // Returns 'active'\n * ```\n */\nexport function getOperationAuthority(op: Operation): AuthorityLevel {\n const opType = op[0];\n\n // Special handling for custom_json - requires content inspection\n if (opType === 'custom_json') {\n return getCustomJsonAuthority(op);\n }\n\n // Special handling for proposal operations - requires content inspection\n if (opType === 'create_proposal' || opType === 'update_proposal') {\n return getProposalAuthority(op);\n }\n\n // Use mapping for standard operations, default to posting if unknown\n return OPERATION_AUTHORITY_MAP[opType] ?? 'posting';\n}\n\n/**\n * Determines the highest authority level required for a list of operations.\n *\n * Useful when broadcasting multiple operations together - the highest authority\n * level required by any operation determines what key is needed for the batch.\n *\n * Authority hierarchy: owner > active > posting > memo\n *\n * @param ops - Array of operations\n * @returns Highest authority level required ('owner', 'active', or 'posting')\n *\n * @example\n * ```typescript\n * const ops: Operation[] = [\n * ['vote', { ... }], // posting\n * ['comment', { ... }], // posting\n * ];\n * getRequiredAuthority(ops); // Returns 'posting'\n *\n * const mixedOps: Operation[] = [\n * ['comment', { ... }], // posting\n * ['transfer', { ... }], // active\n * ];\n * getRequiredAuthority(mixedOps); // Returns 'active'\n *\n * const securityOps: Operation[] = [\n * ['transfer', { ... }], // active\n * ['change_recovery_account', { ... }], // owner\n * ];\n * getRequiredAuthority(securityOps); // Returns 'owner'\n * ```\n */\nexport function getRequiredAuthority(ops: Operation[]): AuthorityLevel {\n let highestAuthority: AuthorityLevel = 'posting';\n\n for (const op of ops) {\n const authority = getOperationAuthority(op);\n\n // Owner is highest - return immediately\n if (authority === 'owner') {\n return 'owner';\n }\n\n // Active is higher than posting\n if (authority === 'active' && highestAuthority === 'posting') {\n highestAuthority = 'active';\n }\n\n // Memo is lowest (same level as posting)\n // If we see memo but only have posting, stick with posting\n }\n\n return highestAuthority;\n}\n","import { PrivateKey } from \"../../../hive-tx\";\nimport type { Operation } from \"../../../hive-tx\";\nimport { isWif, broadcastOperations } from \"@/modules/core/hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\n\nexport function useSignOperationByKey(username: string | undefined) {\n return useMutation({\n mutationKey: [\"operations\", \"sign\", username],\n mutationFn: ({\n operation,\n keyOrSeed,\n }: {\n operation: Operation;\n keyOrSeed: string;\n }) => {\n if (!username) {\n throw new Error(\"[Operations][Sign] – cannot sign op with anon user\");\n }\n\n let privateKey: PrivateKey;\n if (keyOrSeed.split(\" \").length === 12) {\n privateKey = PrivateKey.fromLogin(username, keyOrSeed, \"active\");\n } else if (isWif(keyOrSeed)) {\n privateKey = PrivateKey.fromString(keyOrSeed);\n } else {\n privateKey = PrivateKey.from(keyOrSeed);\n }\n\n return broadcastOperations(\n [operation],\n privateKey\n );\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport function useSignOperationByKeychain(\n username: string | undefined,\n auth?: AuthContextV2,\n keyType: \"owner\" | \"active\" | \"posting\" | \"memo\" = \"active\"\n) {\n return useMutation({\n mutationKey: [\"operations\", \"sign-keychain\", username],\n mutationFn: ({ operation }: { operation: Operation }) => {\n if (!username) {\n throw new Error(\n \"[SDK][Keychain] – cannot sign operation with anon user\"\n );\n }\n if (!auth?.adapter?.broadcastWithKeychain) {\n throw new Error(\"[SDK][Keychain] – missing keychain broadcaster\");\n }\n\n return auth.adapter.broadcastWithKeychain(username, [operation], keyType);\n },\n });\n}\n","import type { Operation } from \"../../../hive-tx\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function useSignOperationByHivesigner(callbackUri = \"/\") {\n return useMutation({\n mutationKey: [\"operations\", \"sign-hivesigner\", callbackUri],\n mutationFn: async ({ operation }: { operation: Operation }) => {\n return hs.sendOperation(operation, { callback: callbackUri }, () => {});\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getChainPropertiesQueryOptions() {\n return queryOptions({\n queryKey: [\"operations\", \"chain-properties\"],\n queryFn: async () => {\n return await callRPC(\"condenser_api.get_chain_properties\", []);\n },\n });\n}\n","import { Fragment } from \"../types\";\n\n/**\n * Build the cache entry for an edited fragment.\n *\n * The `/private-api/fragments-update` endpoint returns only a minimal\n * acknowledgement, not the full fragment. Writing that response straight into\n * the query cache blanked out the edited snippet (the reported bug), so the\n * updated record is built from the values the user actually submitted, merged\n * over whatever fields the response does carry, on top of the existing cached\n * fragment (preserving id/created).\n */\nexport function applyFragmentUpdate(\n existing: Fragment,\n response: Partial | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...existing,\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n };\n}\n\n/**\n * Build the cache entry for a newly added fragment. Reaffirms the submitted\n * title/body over the server acknowledgement so a fresh snippet never renders\n * blank if the response omits them, while keeping any server-provided\n * id/timestamps.\n */\nexport function buildAddedFragment(\n response: Fragment | null | undefined,\n vars: { title: string; body: string }\n): Fragment {\n return {\n ...(response ?? {}),\n title: vars.title,\n body: vars.body\n } as Fragment;\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { buildAddedFragment } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useAddFragment(username: string, code: string | undefined) {\n return useMutation({\n mutationKey: [\"posts\", \"add-fragment\", username],\n mutationFn: async ({ title, body }: { title: string; body: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-add\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and insert a bogus fragment into the cache. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to add fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // Reaffirm the submitted title/body over the server acknowledgement so a\n // freshly added snippet never renders blank if the response omits them,\n // while keeping any server-provided id/timestamps.\n const newFragment = buildAddedFragment(response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [newFragment, ...(data ?? [])]\n );\n\n // Update infinite query cache - add new fragment to first page\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page, index) =>\n index === 0\n ? { ...page, data: [newFragment, ...page.data] }\n : page\n ),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { applyFragmentUpdate } from \"../utils/fragment-cache-helpers\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useEditFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"edit-fragment\", username],\n mutationFn: async ({\n fragmentId,\n title,\n body\n }: {\n fragmentId: string;\n title: string;\n body: string;\n }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/fragments-update\",\n {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n title,\n body,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n // Raw fetch resolves on 4xx/5xx, so a JSON error response would otherwise run\n // onSuccess and overwrite the cached fragment with bogus data. Throw instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to update fragment: ${response.status}`);\n }\n return response.json() as Promise;\n },\n onSuccess(response, variables) {\n const queryClient = getQueryClient();\n\n // The /fragments-update endpoint returns a minimal acknowledgement, not the\n // full fragment, so writing the raw response into the cache blanked out the\n // edited snippet. Rebuild the fragment from the submitted values instead.\n const applyUpdate = (fragment: Fragment): Fragment =>\n applyFragmentUpdate(fragment, response, variables);\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) =>\n data?.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ) ?? []\n );\n\n // Update infinite query cache - update fragment in all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.map((fragment) =>\n fragment.id === variables.fragmentId ? applyUpdate(fragment) : fragment\n ),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { Fragment } from \"../types\";\nimport { getFragmentsQueryOptions } from \"../queries\";\nimport { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useRemoveFragment(\n username: string,\n code: string | undefined\n) {\n return useMutation({\n mutationKey: [\"posts\", \"remove-fragment\", username],\n mutationFn: async ({ fragmentId }: { fragmentId: string }) => {\n if (!code) {\n throw new Error(\"[SDK][Posts] Missing access token\");\n }\n const fetchApi = getBoundFetch();\n\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/fragments-delete\", {\n method: \"POST\",\n body: JSON.stringify({\n code,\n id: fragmentId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // getBoundFetch returns the raw fetch, so a 401/403/500 resolves rather than\n // rejects. Without this guard onSuccess would run and strip the fragment from\n // cache on a failed delete (false success). Throw so onError fires instead.\n if (!response.ok) {\n throw new Error(`[SDK][Posts] Failed to delete fragment: ${response.status}`);\n }\n\n return response;\n },\n onSuccess(_data, variables) {\n const queryClient = getQueryClient();\n\n // Update regular query cache\n queryClient.setQueryData(\n getFragmentsQueryOptions(username, code).queryKey,\n (data) => [...(data ?? [])].filter(({ id }) => id !== variables.fragmentId)\n );\n\n // Update infinite query cache - remove fragment from all pages\n queryClient.setQueriesData>>(\n { queryKey: [\"posts\", \"fragments\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((fragment) => fragment.id !== variables.fragmentId),\n })),\n };\n }\n );\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { ApiNotification, ApiNotificationSetting } from \"@/modules/notifications\";\nimport { Draft, DraftMetadata } from \"@/modules/posts/types/draft\";\nimport { Schedule } from \"@/modules/posts/types/schedule\";\nimport { ApiResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n if (!response.ok) {\n let errorData: unknown = undefined;\n try {\n errorData = await response.json();\n } catch {\n errorData = undefined;\n }\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = errorData;\n throw error;\n }\n\n // Handle empty responses gracefully (e.g., 204 No Content or empty body)\n const text = await response.text();\n if (!text || text.trim() === \"\") {\n return \"\" as T;\n }\n\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n // If JSON parsing fails, return empty string as fallback\n console.warn(\"[SDK] Failed to parse JSON response:\", e, \"Response:\", text);\n return \"\" as T;\n }\n}\n\nexport async function signUp(\n username: string,\n email: string,\n referral: string,\n captchaToken?: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/account-create\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, email, referral, captcha_token: captchaToken }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function subscribeEmail(\n email: string\n): Promise>> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/subscribe\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ email }),\n });\n\n const data = await parseJsonResponse>(response);\n return { status: response.status, data };\n}\n\nexport async function usrActivity(\n code: string | undefined,\n ty: number,\n bl: string | number = \"\",\n tx: string | number = \"\"\n): Promise {\n const params: {\n code: string | undefined;\n ty: number;\n bl?: string | number;\n tx?: string | number;\n } = { code, ty };\n\n if (bl) {\n params.bl = bl;\n }\n if (tx) {\n params.tx = tx;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/usr-activity\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params),\n });\n\n await parseJsonResponse(response);\n}\n\nexport async function getNotifications(\n code: string | undefined,\n filter: string | null,\n since: string | null = null,\n user: string | null = null\n): Promise {\n const data: { code: string | undefined; filter?: string; since?: string; user?: string } = {\n code,\n };\n\n if (filter) {\n data.filter = filter;\n }\n\n if (since) {\n data.since = since;\n }\n\n if (user) {\n data.user = user;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function saveNotificationSetting(\n code: string | undefined,\n username: string,\n system: string,\n allows_notify: number,\n notify_types: number[],\n token: string\n): Promise {\n const data = {\n code,\n username,\n token,\n system,\n allows_notify,\n notify_types,\n };\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/register-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getNotificationSetting(\n code: string | undefined,\n username: string,\n token: string\n): Promise {\n const data = { code, username, token };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/detail-device\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function markNotifications(\n code: string | undefined,\n id?: string\n): Promise> {\n const data: { code: string | undefined; id?: string } = {\n code,\n };\n if (id) {\n data.id = id;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/notifications/mark\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addImage(code: string | undefined, url: string): Promise> {\n const data = { code, url };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\n// Upload always targets the canonical Ecency image server, even when\n// the user has changed their viewing proxy (e.g. images.hive.blog).\n// i.ecency.com is the same imagehoster endpoint as images.ecency.com\n// (identical backend / token validation); it is the canonical host\n// because some ISPs SNI-filter the images.ecency.com hostname.\nconst UPLOAD_HOST = \"https://i.ecency.com\";\n\nexport async function uploadImage(\n file: File,\n token: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${UPLOAD_HOST}/hs/${token}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\n/**\n * Upload image using posting key signature (/:username/:signature path).\n * Works with any compatible image server (images.ecency.com, images.hive.blog).\n * The signature is sha256(\"ImageSigningChallenge\" + fileData) signed with the posting key.\n */\nexport async function uploadImageWithSignature(\n file: File,\n username: string,\n signature: string,\n signal?: AbortSignal\n): Promise<{ url: string }> {\n const fetchApi = getBoundFetch();\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const response = await fetchApi(`${CONFIG.imageHost}/${username}/${signature}`, {\n method: \"POST\",\n body: formData,\n signal,\n });\n\n return parseJsonResponse<{ url: string }>(response);\n}\n\nexport async function deleteImage(\n code: string | undefined,\n imageId: string\n): Promise> {\n const data = { code, id: imageId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/images-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addDraft(\n code: string | undefined,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function updateDraft(\n code: string | undefined,\n draftId: string,\n title: string,\n body: string,\n tags: string,\n meta: DraftMetadata\n): Promise<{ drafts: Draft[] }> {\n const data = { code, id: draftId, title, body, tags, meta };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ drafts: Draft[] }>(response);\n}\n\nexport async function deleteDraft(\n code: string | undefined,\n draftId: string\n): Promise> {\n const data = { code, id: draftId };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/drafts-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function addSchedule(\n code: string | undefined,\n permlink: string,\n title: string,\n body: string,\n meta: Record,\n options: Record | null,\n schedule: string,\n reblog: boolean\n): Promise> {\n const data: Record = {\n code,\n permlink,\n title,\n body,\n meta,\n schedule,\n reblog,\n };\n\n if (options) {\n data.options = options;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-add\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function deleteSchedule(\n code: string | undefined,\n id: string\n): Promise> {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-delete\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse>(response);\n}\n\nexport async function moveSchedule(code: string | undefined, id: string): Promise {\n const data = { code, id };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/schedules-move\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse(response);\n}\n\nexport async function getPromotedPost(\n code: string | undefined,\n author: string,\n permlink: string\n): Promise<{ author: string; permlink: string } | \"\"> {\n const data = { code, author, permlink };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/promoted-post\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n });\n\n return parseJsonResponse<{ author: string; permlink: string } | \"\">(response);\n}\n\nexport async function onboardEmail(\n username: string,\n email: string,\n friend: string\n): Promise> {\n const dataBody = {\n username,\n email,\n friend,\n };\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/account-create-friend\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(dataBody),\n }\n );\n\n return parseJsonResponse>(response);\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useAddDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"add\", username],\n mutationFn: async ({\n title,\n body,\n tags,\n meta,\n }: {\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addDraft\");\n }\n return addDraft(code, title, body, tags, meta);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full drafts list from the response (API returns complete list)\n if (data?.drafts) {\n qc.setQueryData(QueryKeys.posts.drafts(username), data.drafts);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n }\n // Also invalidate the infinite query so the drafts list refetches\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { updateDraft } from \"@/modules/private-api/requests\";\nimport { DraftMetadata } from \"../types\";\n\nexport function useUpdateDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"update\", username],\n mutationFn: async ({\n draftId,\n title,\n body,\n tags,\n meta,\n }: {\n draftId: string;\n title: string;\n body: string;\n tags: string;\n meta: DraftMetadata;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for updateDraft\");\n }\n return updateDraft(code, draftId, title, body, tags, meta);\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError,\n });\n}\n","import { InfiniteData, useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteDraft } from \"@/modules/private-api/requests\";\nimport type { Draft } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\nexport function useDeleteDraft(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"drafts\", \"delete\", username],\n mutationFn: async ({ draftId }: { draftId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteDraft\");\n }\n return deleteDraft(code, draftId);\n },\n onMutate: async ({ draftId }) => {\n if (!username) {\n return;\n }\n\n const qc = getQueryClient();\n const listKey = QueryKeys.posts.drafts(username);\n const infinitePrefix = QueryKeys.posts.draftsInfinite(username);\n\n await Promise.all([\n qc.cancelQueries({ queryKey: listKey }),\n qc.cancelQueries({ queryKey: infinitePrefix }),\n ]);\n\n const previousList = qc.getQueryData(listKey);\n if (previousList) {\n qc.setQueryData(\n listKey,\n previousList.filter((d) => d._id !== draftId)\n );\n }\n\n const infiniteQueries = qc.getQueriesData>>({\n queryKey: infinitePrefix,\n });\n const previousInfinite = new Map(infiniteQueries);\n for (const [key, data] of infiniteQueries) {\n if (data) {\n qc.setQueryData(key, {\n ...data,\n pages: data.pages.map((page) => ({\n ...page,\n data: page.data.filter((d) => d._id !== draftId),\n })),\n });\n }\n }\n\n return { previousList, previousInfinite };\n },\n onSuccess: () => {\n onSuccess?.();\n const qc = getQueryClient();\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n qc.invalidateQueries({ queryKey: QueryKeys.posts.draftsInfinite(username) });\n },\n onError: (err, _variables, context) => {\n const qc = getQueryClient();\n if (context?.previousList) {\n qc.setQueryData(QueryKeys.posts.drafts(username), context.previousList);\n }\n if (context?.previousInfinite) {\n for (const [key, data] of context.previousInfinite) {\n qc.setQueryData(key, data);\n }\n }\n onError?.(err);\n },\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addSchedule } from \"@/modules/private-api/requests\";\n\nexport function useAddSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"add\", username],\n mutationFn: async ({\n permlink,\n title,\n body,\n meta,\n options,\n schedule,\n reblog,\n }: {\n permlink: string;\n title: string;\n body: string;\n meta: Record;\n options: Record | null;\n schedule: string;\n reblog: boolean;\n }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for addSchedule\");\n }\n return addSchedule(code, permlink, title, body, meta, options, schedule, reblog);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.schedules(username),\n });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { deleteSchedule } from \"@/modules/private-api/requests\";\n\nexport function useDeleteSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"delete\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteSchedule\");\n }\n return deleteSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { moveSchedule } from \"@/modules/private-api/requests\";\n\nexport function useMoveSchedule(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"schedules\", \"move\", username],\n mutationFn: async ({ id }: { id: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for moveSchedule\");\n }\n return moveSchedule(code, id);\n },\n onSuccess: (data) => {\n onSuccess?.();\n const qc = getQueryClient();\n // Set the full schedules list from the response (API returns complete list)\n if (data) {\n qc.setQueryData(QueryKeys.posts.schedules(username), data);\n } else {\n qc.invalidateQueries({ queryKey: QueryKeys.posts.schedules(username) });\n }\n // Also invalidate drafts since moving a schedule creates a draft\n qc.invalidateQueries({ queryKey: QueryKeys.posts.drafts(username) });\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { addImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to add an image URL to the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful addition\n * @param onError - Optional callback on error\n *\n * @example\n * const addImageMutation = useAddImage(username, code);\n * addImageMutation.mutate({ url: 'https://...' });\n */\nexport function useAddImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"add\", username],\n mutationFn: async ({ url, code: nextCode }: { url: string; code?: string }) => {\n const effectiveCode = nextCode ?? code;\n\n if (!username || !effectiveCode) {\n throw new Error(\"[SDK][Posts] – missing auth for addImage\");\n }\n return addImage(effectiveCode, url);\n },\n onSuccess: () => {\n onSuccess?.();\n getQueryClient().invalidateQueries({\n queryKey: QueryKeys.posts.images(username),\n });\n },\n onError,\n });\n}\n","import { useMutation, type InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport { deleteImage } from \"@/modules/private-api/requests\";\nimport type { UserImage } from \"../types\";\nimport type { WrappedResponse } from \"@/modules/core/types\";\n\n/**\n * Hook to delete an image from the user's Ecency gallery\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful deletion\n * @param onError - Optional callback on error\n *\n * @example\n * const deleteImageMutation = useDeleteImage(username, code);\n * deleteImageMutation.mutate({ imageId: '123' });\n */\nexport function useDeleteImage(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: () => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"delete\", username],\n mutationFn: async ({ imageId }: { imageId: string }) => {\n if (!username || !code) {\n throw new Error(\"[SDK][Posts] – missing auth for deleteImage\");\n }\n return deleteImage(code, imageId);\n },\n onSuccess: (_data, variables) => {\n onSuccess?.();\n const qc = getQueryClient();\n const { imageId } = variables;\n\n // Optimistic removal from regular cache\n qc.setQueryData(\n [\"posts\", \"images\", username],\n (prev) => prev?.filter((img) => img._id !== imageId)\n );\n\n // Optimistic removal from infinite cache pages\n qc.setQueriesData>>(\n { queryKey: [\"posts\", \"images\", \"infinite\", username] },\n (oldData) => {\n if (!oldData) return oldData;\n return {\n ...oldData,\n pages: oldData.pages.map((page) => ({\n ...page,\n data: page.data.filter((img) => img._id !== imageId),\n })),\n };\n }\n );\n },\n onError,\n });\n}\n","import { useMutation } from \"@tanstack/react-query\";\nimport { uploadImage } from \"@/modules/private-api/requests\";\n\n/**\n * Hook to upload an image file to Ecency image hosting\n *\n * @param onSuccess - Optional callback on successful upload, receives { url: string }\n * @param onError - Optional callback on error\n *\n * Note: This hook uploads to Ecency's image server and requires a signature token.\n * The token should be generated using the user's posting key signature.\n *\n * @example\n * const uploadMutation = useUploadImage(\n * (data) => console.log('Uploaded:', data.url)\n * );\n * uploadMutation.mutate({ file, token });\n */\nexport function useUploadImage(\n onSuccess?: (data: { url: string }) => void,\n onError?: (e: Error) => void\n) {\n return useMutation({\n mutationKey: [\"posts\", \"images\", \"upload\"],\n mutationFn: async ({\n file,\n token,\n signal,\n }: {\n file: File;\n token: string;\n signal?: AbortSignal;\n }) => {\n return uploadImage(file, token, signal);\n },\n onSuccess,\n onError,\n });\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry, EntryVote } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\nfunction makeEntryPath(author: string, permlink: string) {\n return `/@${author}/${permlink}`;\n}\n\nfunction getEntryFromCache(\n author: string,\n permlink: string,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n return queryClient.getQueryData(\n QueryKeys.posts.entry(makeEntryPath(author, permlink))\n );\n}\n\nfunction setEntryInCache(entry: Entry, qc?: QueryClient) {\n const queryClient = qc ?? getQueryClient();\n queryClient.setQueryData(\n QueryKeys.posts.entry(makeEntryPath(entry.author, entry.permlink)),\n entry\n );\n}\n\nfunction mutateEntry(\n author: string,\n permlink: string,\n updater: (entry: Entry) => Entry,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = makeEntryPath(author, permlink);\n const existing = queryClient.getQueryData(QueryKeys.posts.entry(path));\n if (!existing) return undefined;\n\n const updated = updater(existing);\n queryClient.setQueryData(QueryKeys.posts.entry(path), updated);\n return existing;\n}\n\n/**\n * SDK-level entry cache utilities. These operate on SDK cache keys\n * ([\"posts\", \"entry\", \"/@author/permlink\"]).\n *\n * Web layer can bridge these to its own QueryIdentifiers.ENTRY keys\n * during the migration period.\n */\nexport namespace EntriesCacheManagement {\n export function updateVotes(\n author: string,\n permlink: string,\n votes: EntryVote[],\n payout: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n active_votes: votes,\n stats: {\n ...(entry.stats || {\n gray: false,\n hide: false,\n flag_weight: 0,\n total_votes: 0,\n }),\n total_votes: votes.length,\n flag_weight: entry.stats?.flag_weight || 0,\n },\n total_votes: votes.length,\n payout,\n pending_payout_value: String(payout),\n }),\n qc\n );\n }\n\n export function updateReblogsCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n reblogs: count,\n }),\n qc\n );\n }\n\n export function updateRepliesCount(\n author: string,\n permlink: string,\n count: number,\n qc?: QueryClient\n ) {\n mutateEntry(\n author,\n permlink,\n (entry) => ({\n ...entry,\n children: count,\n }),\n qc\n );\n }\n\n export function addReply(\n reply: Entry,\n parentAuthor: string,\n parentPermlink: string,\n qc?: QueryClient\n ) {\n mutateEntry(\n parentAuthor,\n parentPermlink,\n (entry) => ({\n ...entry,\n children: entry.children + 1,\n replies: [reply, ...entry.replies],\n }),\n qc\n );\n }\n\n export function updateEntries(entries: Entry[], qc?: QueryClient) {\n entries.forEach((entry) => setEntryInCache(entry, qc));\n }\n\n export function invalidateEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ) {\n const queryClient = qc ?? getQueryClient();\n queryClient.invalidateQueries({\n queryKey: QueryKeys.posts.entry(makeEntryPath(author, permlink)),\n });\n }\n\n export function getEntry(\n author: string,\n permlink: string,\n qc?: QueryClient\n ): Entry | undefined {\n return getEntryFromCache(author, permlink, qc);\n }\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Whether the cached active_votes list already reflects the broadcast vote:\n * the voter is present for a vote (weight !== 0) or absent for an unvote\n * (weight === 0). Used to avoid stacking the SDK's post-broadcast optimistic\n * update on top of a platform-level optimistic update applied at press time.\n */\nexport function isVoteAlreadyReflected(\n activeVotes: Array<{ voter: string }>,\n voter: string | undefined,\n weight: number\n): boolean {\n const hasVoterRecord = activeVotes.some((v) => v.voter === voter);\n return weight !== 0 ? hasVoterRecord : !hasVoterRecord;\n}\n\n/**\n * Payload for voting on a post or comment.\n */\nexport interface VotePayload {\n /** Author of the post/comment to vote on */\n author: string;\n /** Permlink of the post/comment to vote on */\n permlink: string;\n /** Vote weight (-10000 to 10000, where 10000 = 100% upvote, -10000 = 100% downvote) */\n weight: number;\n /** Optional estimated payout change for optimistic UI */\n estimated?: number;\n}\n\n/**\n * Post-broadcast optimistic cache update for a vote: replaces the voter's\n * active_votes record and bumps the payout by `estimated`. Skipped when the\n * cached entry already reflects this vote (voter present for a vote, absent\n * for an unvote): platforms with their own at-press optimistic layer (e.g.\n * the mobile app) have applied it by the time the broadcast resolves, and\n * stacking a second update here double-counts the payout and clobbers the\n * platform's richer vote record until the deferred invalidation.\n */\nexport function applyVoteCacheUpdate(\n username: string | undefined,\n variables: VotePayload,\n qc?: QueryClient\n): void {\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink, qc);\n if (\n !entry?.active_votes ||\n isVoteAlreadyReflected(entry.active_votes, username, variables.weight)\n ) {\n return;\n }\n const newVotes = [\n ...entry.active_votes.filter((v) => v.voter !== username),\n ...(variables.weight !== 0 ? [{ rshares: variables.weight, voter: username! }] : [])\n ];\n const newPayout = entry.payout + (variables.estimated ?? 0);\n EntriesCacheManagement.updateVotes(\n variables.author,\n variables.permlink,\n newVotes,\n newPayout,\n qc\n );\n}\n\n/**\n * React Query mutation hook for voting on posts and comments.\n *\n * This mutation broadcasts a vote operation to the Hive blockchain,\n * supporting upvotes (positive weight) and downvotes (negative weight).\n *\n * @param username - The username of the voter (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 120) if adapter.recordActivity is available\n * - Invalidates post cache to refetch updated vote data\n * - Invalidates voting power cache to show updated VP\n *\n * **Vote Weight:**\n * - 10000 = 100% upvote\n * - 0 = remove vote\n * - -10000 = 100% downvote\n *\n * @example\n * ```typescript\n * const voteMutation = useVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Upvote a post\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 10000\n * });\n *\n * // Remove vote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: 0\n * });\n *\n * // Downvote\n * voteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * weight: -10000\n * });\n * ```\n *\n * @remarks\n * broadcastMode: async — Votes don't require block confirmation.\n * The vote is accepted into the mempool immediately; UI can optimistically update.\n */\nexport function useVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"vote\"],\n username,\n ({ author, permlink, weight }) => [\n buildVoteOp(username!, author, permlink, weight)\n ],\n async (result: any, variables) => {\n // Optimistic vote list + payout update (no-op when the cache already\n // reflects this vote — see applyVoteCacheUpdate).\n applyVoteCacheUpdate(username, variables);\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(120, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n if (auth?.adapter?.invalidateQueries) {\n const doInvalidate = () => {\n auth.adapter!.invalidateQueries!([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.accounts.full(username)\n ]);\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(doInvalidate, 4000);\n } else {\n doInvalidate();\n }\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildReblogOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EntriesCacheManagement } from \"../cache/entries-cache-management\";\n\n/**\n * Payload for reblogging a post.\n */\nexport interface ReblogPayload {\n /** Original post author */\n author: string;\n /** Original post permlink */\n permlink: string;\n /** If true, removes the reblog instead of creating it */\n deleteReblog?: boolean;\n}\n\n/**\n * React Query mutation hook for reblogging posts.\n *\n * This mutation broadcasts a custom_json operation to reblog (or un-reblog)\n * a post to the user's blog feed.\n *\n * @param username - The username performing the reblog (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 130) if adapter.recordActivity is available\n * - Invalidates blog feed cache to show the reblogged post\n * - Invalidates post cache to update reblog status\n *\n * **Reblog vs Delete:**\n * - deleteReblog: false (default) - Creates a reblog\n * - deleteReblog: true - Removes an existing reblog\n *\n * @example\n * ```typescript\n * const reblogMutation = useReblog(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Reblog a post\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post'\n * });\n *\n * // Remove a reblog\n * reblogMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post',\n * deleteReblog: true\n * });\n * ```\n */\nexport function useReblog(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"reblog\"],\n username,\n ({ author, permlink, deleteReblog }) => [\n buildReblogOp(username!, author, permlink, deleteReblog ?? false)\n ],\n async (result: any, variables) => {\n // Optimistic reblog count update\n const entry = EntriesCacheManagement.getEntry(variables.author, variables.permlink);\n if (entry) {\n const newCount = Math.max(0, (entry.reblogs ?? 0) + (variables.deleteReblog ? -1 : 1));\n EntriesCacheManagement.updateReblogsCount(variables.author, variables.permlink, newCount);\n }\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(130, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation — deferred for async broadcasts since onSuccess fires\n // at mempool acceptance before block inclusion.\n const invalidate = () => {\n const qc = getQueryClient();\n qc.invalidateQueries({\n queryKey: QueryKeys.posts.accountPostsBlogPrefix(username!),\n });\n if (auth?.adapter?.invalidateQueries) {\n auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n QueryKeys.posts.rebloggedBy(variables.author, variables.permlink),\n ]);\n }\n };\n const mode = broadcastMode ?? 'async';\n if (mode === 'async') {\n setTimeout(invalidate, 4000);\n } else {\n invalidate();\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Beneficiary account and weight.\n */\nexport interface Beneficiary {\n /** Beneficiary account name */\n account: string;\n /** Beneficiary weight (10000 = 100%) */\n weight: number;\n}\n\n/**\n * Payload for creating a comment or post.\n */\nexport interface CommentPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post */\n permlink: string;\n /** Parent author (empty string for top-level posts) */\n parentAuthor: string;\n /** Parent permlink (category/tag for top-level posts) */\n parentPermlink: string;\n /** Title of the post (empty for comments) */\n title: string;\n /** Content body */\n body: string;\n /** JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for creating posts and comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to create a new post or reply on the Hive blockchain.\n *\n * @param username - The username creating the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 100 for posts, 110 for comments) if adapter.recordActivity is available\n * - Invalidates feed caches to show the new content\n * - Invalidates parent post cache if this is a reply\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Post vs Comment:**\n * - Post: parentAuthor = \"\", parentPermlink = category/tag\n * - Comment: parentAuthor = parent author, parentPermlink = parent permlink\n *\n * @example\n * ```typescript\n * const commentMutation = useComment(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a post\n * commentMutation.mutate({\n * author: 'alice',\n * permlink: 'my-awesome-post-20260209',\n * parentAuthor: '',\n * parentPermlink: 'technology',\n * title: 'My Awesome Post',\n * body: 'This is the post content...',\n * jsonMetadata: {\n * tags: ['technology', 'hive'],\n * app: 'ecency/3.0.0'\n * },\n * options: {\n * beneficiaries: [\n * { account: 'ecency', weight: 500 }\n * ]\n * }\n * });\n *\n * // Create a comment\n * commentMutation.mutate({\n * author: 'bob',\n * permlink: 're-alice-my-awesome-post-20260209',\n * parentAuthor: 'alice',\n * parentPermlink: 'my-awesome-post-20260209',\n * title: '',\n * body: 'Great post!',\n * jsonMetadata: { app: 'ecency/3.0.0' }\n * });\n * ```\n */\nexport function useComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"comment\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (result: any, variables) => {\n // Determine if this is a post or comment\n const isPost = !variables.parentAuthor;\n const activityType = isPost ? 100 : 110;\n\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(activityType, txId, result?.block_num).catch(() => {});\n }\n\n // Cache invalidation (always runs regardless of recordActivity outcome)\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (!isPost) {\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { Entry } from \"../types\";\nimport type { QueryClient } from \"@tanstack/react-query\";\n\n/**\n * Adds an optimistic entry to all discussions caches for the given root post.\n * Uses predicate matching to find all sort order variants.\n */\nexport function addOptimisticDiscussionEntry(\n entry: Entry,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n queryClient.setQueryData(queryKey, [entry, ...data]);\n }\n }\n}\n\n/**\n * Removes an entry from all discussions caches for the given root post.\n * Returns the previous state for rollback.\n */\nexport function removeOptimisticDiscussionEntry(\n author: string,\n permlink: string,\n rootAuthor: string,\n rootPermlink: string,\n qc?: QueryClient\n): Map {\n const queryClient = qc ?? getQueryClient();\n const snapshots = new Map();\n\n const queries = queryClient.getQueriesData({\n predicate: (query) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === rootAuthor &&\n key[3] === rootPermlink\n );\n },\n });\n\n for (const [queryKey, data] of queries) {\n if (data) {\n snapshots.set(queryKey, data);\n queryClient.setQueryData(\n queryKey,\n data.filter(\n (e) => e.author !== author || e.permlink !== permlink\n )\n );\n }\n }\n\n return snapshots;\n}\n\n/**\n * Restores discussion cache snapshots (for rollback on error).\n */\nexport function restoreDiscussionSnapshots(\n snapshots: Map,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n for (const [queryKey, data] of snapshots) {\n queryClient.setQueryData(queryKey, data);\n }\n}\n\n/**\n * Updates a specific entry in the SDK entry cache.\n * Returns the previous entry for rollback.\n */\nexport function updateEntryInCache(\n author: string,\n permlink: string,\n updates: Partial,\n qc?: QueryClient\n): Entry | undefined {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n const previous = queryClient.getQueryData(QueryKeys.posts.entry(path));\n\n if (previous) {\n queryClient.setQueryData(QueryKeys.posts.entry(path), {\n ...previous,\n ...updates,\n });\n }\n\n return previous;\n}\n\n/**\n * Restores an entry in cache (for rollback on error).\n */\nexport function restoreEntryInCache(\n author: string,\n permlink: string,\n entry: Entry,\n qc?: QueryClient\n) {\n const queryClient = qc ?? getQueryClient();\n const path = `/@${author}/${permlink}`;\n queryClient.setQueryData(QueryKeys.posts.entry(path), entry);\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDeleteCommentOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport {\n removeOptimisticDiscussionEntry,\n restoreDiscussionSnapshots,\n} from \"../cache/discussions-cache-utils\";\nimport type { Entry } from \"../types\";\n\n/**\n * Payload for deleting a comment or post.\n */\nexport interface DeleteCommentPayload {\n /** Author of the comment/post to delete */\n author: string;\n /** Permlink of the comment/post to delete */\n permlink: string;\n /** Optional: Parent author (for cache invalidation of discussions) */\n parentAuthor?: string;\n /** Optional: Parent permlink (for cache invalidation of discussions) */\n parentPermlink?: string;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n}\n\n/**\n * React Query mutation hook for deleting posts and comments.\n *\n * This mutation broadcasts a delete_comment operation to the Hive blockchain.\n * Includes optimistic removal from discussions cache with rollback on error.\n *\n * @param username - The username deleting the comment/post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n */\nexport function useDeleteComment(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"deleteComment\"],\n username,\n ({ author, permlink }) => [\n buildDeleteCommentOp(author, permlink)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username)\n ];\n\n // If this is a reply, invalidate parent post and discussions\n if (variables.parentAuthor && variables.parentPermlink) {\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n }\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n {\n broadcastMode,\n // Optimistic removal: remove from discussions cache before broadcast\n onMutate: async (variables) => {\n const rootAuthor = variables.rootAuthor || variables.parentAuthor;\n const rootPermlink = variables.rootPermlink || variables.parentPermlink;\n\n if (rootAuthor && rootPermlink) {\n const snapshots = removeOptimisticDiscussionEntry(\n variables.author,\n variables.permlink,\n rootAuthor,\n rootPermlink\n );\n return { snapshots };\n }\n return {};\n },\n // Rollback on error: restore discussions cache\n onError: (_error, _variables, context) => {\n const { snapshots } = (context as { snapshots?: Map }) ?? {};\n if (snapshots) {\n restoreDiscussionSnapshots(snapshots);\n }\n },\n }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\n/**\n * Payload for creating a cross-post.\n */\nexport interface CrossPostPayload {\n /** Author of the cross-post (current user) */\n author: string;\n /** Permlink of the cross-post (usually: original-permlink-community-id) */\n permlink: string;\n /** Community ID to cross-post to (used as parent_permlink) */\n parentPermlink: string;\n /** Title of the cross-post (same as original) */\n title: string;\n /** Body of the cross-post (includes reference to original) */\n body: string;\n /** JSON metadata (must include original_author, original_permlink, tags, app) */\n jsonMetadata: Record;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"0.000 HBD\" for declined payout) */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n };\n}\n\n/**\n * React Query mutation hook for creating cross-posts.\n *\n * A cross-post is a special type of post that references an original post\n * and publishes it to a different community.\n *\n * @param username - The username creating the cross-post (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates feed/blog caches to show the new cross-post\n *\n * **Operations:**\n * - Always includes a comment operation (with empty parent_author for top-level post)\n * - Optionally includes comment_options operation for rewards/beneficiaries\n *\n * **Metadata Requirements:**\n * The jsonMetadata must include:\n * - `original_author`: Author of the original post\n * - `original_permlink`: Permlink of the original post\n * - `tags`: Tags for the cross-post (typically [\"cross-post\"])\n * - `app`: Application identifier (e.g., \"ecency/3.0.0-vision\")\n *\n * @example\n * ```typescript\n * const crossPostMutation = useCrossPost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Create a cross-post\n * crossPostMutation.mutate({\n * author: 'alice',\n * permlink: 'great-post-hive-123456',\n * parentPermlink: 'hive-123456', // community ID\n * title: 'Great Post',\n * body: 'This is a cross post of [@bob/great-post](/technology/@bob/great-post) by @alice.

Check this out!',\n * jsonMetadata: {\n * app: 'ecency/3.0.0-vision',\n * tags: ['cross-post'],\n * original_author: 'bob',\n * original_permlink: 'great-post'\n * },\n * options: {\n * maxAcceptedPayout: '0.000 HBD',\n * allowCurationRewards: false\n * }\n * });\n * ```\n */\nexport function useCrossPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"cross-post\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (empty parent_author for top-level post)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n \"\", // empty parent_author for top-level post\n payload.parentPermlink, // community ID\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n } = payload.options;\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n [] // No beneficiaries for cross-posts\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.accounts.full(username),\n // Invalidate target community feed so cross-post appears\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.parentPermlink\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommentOp, buildCommentOptionsOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\nimport type { Beneficiary } from \"./use-comment\";\n\n/**\n * Payload for updating a reply/comment.\n */\nexport interface UpdateReplyPayload {\n /** Author of the comment/post */\n author: string;\n /** Permlink of the comment/post being updated */\n permlink: string;\n /** Parent author */\n parentAuthor: string;\n /** Parent permlink */\n parentPermlink: string;\n /** Title (empty for comments) */\n title: string;\n /** Updated content body */\n body: string;\n /** Updated JSON metadata object */\n jsonMetadata: Record;\n /** Optional: Root post author (for nested replies, used for discussions cache invalidation) */\n rootAuthor?: string;\n /** Optional: Root post permlink (for nested replies, used for discussions cache invalidation) */\n rootPermlink?: string;\n /** Optional: Comment options (beneficiaries, rewards) */\n options?: {\n /** Maximum accepted payout (e.g., \"1000000.000 HBD\") */\n maxAcceptedPayout?: string;\n /** Percent of payout in HBD (10000 = 100%) */\n percentHbd?: number;\n /** Allow votes on this content */\n allowVotes?: boolean;\n /** Allow curation rewards */\n allowCurationRewards?: boolean;\n /** Beneficiaries array */\n beneficiaries?: Beneficiary[];\n };\n}\n\n/**\n * React Query mutation hook for updating existing replies/comments.\n *\n * This mutation broadcasts a comment operation (and optionally comment_options)\n * to update an existing reply/comment on the Hive blockchain.\n *\n * @param username - The username updating the comment (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates parent post cache to reflect the updated comment\n * - Invalidates discussions cache (all sort orders)\n * - Invalidates RC cache (RC decreases after updating)\n *\n * **Operations:**\n * - Always includes a comment operation\n * - Optionally includes comment_options operation for beneficiaries/rewards\n *\n * **Important:**\n * - Updates use the same comment operation as creating new comments\n * - The blockchain identifies this as an update based on matching author/permlink\n * - Only the author can update their own content\n * - Content can only be updated before payout (within 7 days)\n *\n * @example\n * ```typescript\n * const updateReplyMutation = useUpdateReply(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update a reply\n * updateReplyMutation.mutate({\n * author: 'alice',\n * permlink: 're-bob-my-post-20260209',\n * parentAuthor: 'bob',\n * parentPermlink: 'my-post-20260209',\n * title: '',\n * body: 'Updated comment content!',\n * jsonMetadata: {\n * tags: ['comment'],\n * app: 'ecency/3.0.0-vision'\n * },\n * rootAuthor: 'bob',\n * rootPermlink: 'my-post-20260209'\n * });\n * ```\n */\nexport function useUpdateReply(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"posts\", \"update-reply\"],\n username,\n (payload) => {\n const operations: Operation[] = [];\n\n // Main comment operation (same operation for create and update)\n operations.push(\n buildCommentOp(\n payload.author,\n payload.permlink,\n payload.parentAuthor,\n payload.parentPermlink,\n payload.title,\n payload.body,\n payload.jsonMetadata\n )\n );\n\n // Optional comment options operation\n if (payload.options) {\n const {\n maxAcceptedPayout = \"1000000.000 HBD\",\n percentHbd = 10000,\n allowVotes = true,\n allowCurationRewards = true,\n beneficiaries = []\n } = payload.options;\n\n const extensions: any[] = [];\n\n // Add beneficiaries extension if provided\n if (beneficiaries.length > 0) {\n // Sort beneficiaries alphabetically by account name (required by blockchain)\n const sortedBeneficiaries = [...beneficiaries].sort((a, b) =>\n a.account.localeCompare(b.account)\n );\n\n extensions.push([\n 0,\n {\n beneficiaries: sortedBeneficiaries.map(b => ({\n account: b.account,\n weight: b.weight\n }))\n }\n ]);\n }\n\n operations.push(\n buildCommentOptionsOp(\n payload.author,\n payload.permlink,\n maxAcceptedPayout,\n percentHbd,\n allowVotes,\n allowCurationRewards,\n extensions\n )\n );\n }\n\n return operations;\n },\n async (_result: any, variables) => {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = _result?.id ?? _result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(110, txId, _result?.block_num).catch((error) => {\n console.debug(\"[SDK][Posts][useUpdateReply] recordActivity failed\", {\n activityType: 110,\n blockNum: _result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n QueryKeys.resourceCredits.account(username!)\n ];\n\n // Invalidate parent entry\n queriesToInvalidate.push(\n QueryKeys.posts.entry(`/@${variables.parentAuthor}/${variables.parentPermlink}`)\n );\n\n // Invalidate discussions (matches all sort orders)\n // Use partial key to match all sort order variants\n // For nested replies, use rootAuthor/rootPermlink to match the root post's discussions\n // Fall back to parentAuthor/parentPermlink for direct replies to posts\n const discussionsAuthor = variables.rootAuthor || variables.parentAuthor;\n const discussionsPermlink = variables.rootPermlink || variables.parentPermlink;\n\n queriesToInvalidate.push({\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"discussions\" &&\n key[2] === discussionsAuthor &&\n key[3] === discussionsPermlink\n );\n }\n });\n\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPromoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for promoting a post using Ecency Points.\n */\nexport interface PromotePayload {\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Promotion duration in days */\n duration: number;\n}\n\n/**\n * React Query mutation hook for promoting posts.\n *\n * This mutation broadcasts a custom_json operation to promote a post\n * using Ecency Points. The post will appear in promoted feeds for the\n * specified duration.\n *\n * @param username - The username promoting the post (required for broadcast, deducts points from this user)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates promoted posts cache to show newly promoted content\n * - Invalidates user points balance\n * - Invalidates post cache to update promotion status\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_promote\"\n * - JSON: {\"user\": \"username\", \"author\": \"postauthor\", \"permlink\": \"postpermlink\", \"duration\": 7}\n * - Authority: Active key (required for point spending)\n *\n * **Cost:**\n * - Costs Ecency Points based on duration\n * - User must have sufficient points balance\n *\n * @example\n * ```typescript\n * const promoteMutation = usePromote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Promote a post for 7 days\n * promoteMutation.mutate({\n * author: 'alice',\n * permlink: 'my-great-post',\n * duration: 7\n * });\n * ```\n */\nexport function usePromote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"ecency\", \"promote\"],\n username,\n ({ author, permlink, duration }) => [\n buildPromoteOp(username!, author, permlink, duration)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate promoted posts feed\n [...QueryKeys.posts._promotedPrefix],\n // Invalidate user points balance\n [...QueryKeys.points._prefix(username!)],\n // Invalidate specific post cache to update promotion status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { Entry } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport type ValidatePostCreatingOptions = {\n delays?: number[];\n};\n\nconst DEFAULT_VALIDATE_POST_DELAYS = [3000, 3000, 3000];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function getContent(author: string, permlink: string): Promise {\n return callRPC(\"condenser_api.get_content\", [\n author,\n permlink,\n ]) as Promise;\n}\n\nexport async function validatePostCreating(\n author: string,\n permlink: string,\n attempts = 0,\n options?: ValidatePostCreatingOptions\n) {\n const delays = options?.delays ?? DEFAULT_VALIDATE_POST_DELAYS;\n\n let response: Entry | undefined;\n try {\n response = await getContent(author, permlink);\n } catch (e) {\n response = undefined;\n }\n\n if (response || attempts >= delays.length) {\n return;\n }\n\n const waitMs = delays[attempts];\n if (waitMs > 0) {\n await delay(waitMs);\n }\n\n return validatePostCreating(author, permlink, attempts + 1, options);\n}\n","export * from \"./use-record-activity\";\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\n\ntype ActivityType =\n // Editor related\n | \"post-created\"\n | \"post-updated\"\n | \"post-scheduled\"\n | \"draft-created\"\n | \"video-published\"\n\n // Legacy editor related\n | \"legacy-post-created\"\n | \"legacy-post-updated\"\n | \"legacy-post-scheduled\"\n | \"legacy-draft-created\"\n | \"legacy-video-published\"\n\n // Perks related\n | \"perks-points-by-qr\"\n | \"perks-account-boost\"\n | \"perks-promote\"\n | \"perks-boost-plus\"\n | \"points-claimed\"\n | \"spin-rolled\"\n\n // Signup related\n | \"signed-up-with-wallets\"\n | \"signed-up-with-email\";\n\nexport interface RecordActivityOptions {\n url?: string;\n domain?: string;\n}\n\n/**\n * Get current location info safely (works in browser and Node.js)\n * Returns empty strings in non-browser environments\n */\nfunction getLocationInfo(): { url: string; domain: string } {\n if (typeof window !== \"undefined\" && window.location) {\n return {\n url: window.location.href,\n domain: window.location.host,\n };\n }\n return { url: \"\", domain: \"\" };\n}\n\nexport function useRecordActivity(\n username: string | undefined,\n activityType: ActivityType,\n options?: RecordActivityOptions\n) {\n return useMutation({\n mutationKey: [\"analytics\", activityType],\n mutationFn: async () => {\n if (!activityType) {\n throw new Error(\"[SDK][Analytics] – no activity type provided\");\n }\n const fetchApi = getBoundFetch();\n\n // Use provided values or auto-detect from browser environment\n // Falls back to empty strings in non-browser environments (Node.js, React Native, etc.)\n const locationInfo = getLocationInfo();\n const url = options?.url ?? locationInfo.url;\n const domain = options?.domain ?? locationInfo.domain;\n\n try {\n await fetchApi(CONFIG.plausibleHost + \"/api/event\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: activityType,\n url,\n domain,\n props: {\n username,\n },\n }),\n });\n } catch {\n // Analytics is fire-and-forget - network failures, ad blockers,\n // and CORS issues should not bubble up as user-facing errors\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { LeaderBoardDuration, LeaderBoardItem } from \"../types\";\n\nexport function getDiscoverLeaderboardQueryOptions(duration: LeaderBoardDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-leaderboard\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/leaderboard/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch leaderboard: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { CurationDuration, CurationItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getDiscoverCurationQueryOptions(duration: CurationDuration) {\n return queryOptions({\n queryKey: [\"analytics\", \"discover-curation\", duration],\n queryFn: async ({ signal }) => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/curation/${duration}`,\n { signal }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch curation data: ${response.status}`);\n }\n\n const data = (await response.json()) as CurationItem[];\n\n // Fetch account data for efficiency calculation\n const accounts = data.map((item) => item.account);\n const accountsResponse = await callRPC(\"condenser_api.get_accounts\", [accounts]);\n\n // Calculate efficiency for each curator\n for (let index = 0; index < accountsResponse.length; index++) {\n const element = accountsResponse[index];\n const curator = data[index];\n\n // Convert Asset to string if needed\n const vestingShares = typeof element.vesting_shares === 'string'\n ? element.vesting_shares\n : element.vesting_shares.toString();\n const receivedVestingShares = typeof element.received_vesting_shares === 'string'\n ? element.received_vesting_shares\n : element.received_vesting_shares.toString();\n const delegatedVestingShares = typeof element.delegated_vesting_shares === 'string'\n ? element.delegated_vesting_shares\n : element.delegated_vesting_shares.toString();\n const vestingWithdrawRate = typeof element.vesting_withdraw_rate === 'string'\n ? element.vesting_withdraw_rate\n : element.vesting_withdraw_rate.toString();\n\n const effectiveVest: number =\n parseFloat(vestingShares) +\n parseFloat(receivedVestingShares) -\n parseFloat(delegatedVestingShares) -\n parseFloat(vestingWithdrawRate);\n // `hp` is the reward in Hive Power; the denominator stays in VESTS, which\n // is what the ranking has always compared. Every curator is scaled the\n // same way, so the ordering is unaffected by the unit mismatch.\n curator.efficiency = curator.hp / effectiveVest;\n }\n\n // Sort by efficiency descending\n data.sort((a: CurationItem, b: CurationItem) => b.efficiency - a.efficiency);\n\n return data;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PageStatsResponse } from \"../types\";\n\n/**\n * Get page statistics from the private analytics API\n *\n * @param url - URL to get stats for\n * @param dimensions - Dimensions to query (default: [])\n * @param metrics - Metrics to query (default: [\"visitors\", \"pageviews\", \"visit_duration\"])\n * @param dateRange - Date range for the query (e.g. \"day\", \"7d\", \"30d\", \"all\")\n */\nexport function getPageStatsQueryOptions(\n url: string,\n dimensions: string[] = [],\n metrics: string[] = [\"visitors\", \"pageviews\", \"visit_duration\"],\n dateRange?: string\n) {\n // Sort arrays to ensure stable query keys regardless of input order\n const sortedDimensions = [...dimensions].sort();\n const sortedMetrics = [...metrics].sort();\n\n return queryOptions({\n queryKey: [\"analytics\", \"page-stats\", url, sortedDimensions, sortedMetrics, dateRange],\n queryFn: async ({ signal }) => {\n const response = await fetch(CONFIG.privateApiHost + \"/api/stats\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n date_range: dateRange,\n }),\n signal,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page stats: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n enabled: !!url,\n // Analytics data should always be fresh - users expect current stats when changing range\n staleTime: 0,\n });\n}\n","/**\n * 3Speak takes an 11% beneficiary share on posts that embed one of its videos.\n *\n * This lives in the SDK because the rule is a payout contract that both the web app and the\n * mobile app have to apply identically. It was previously duplicated in each, which meant a\n * change to the weight, or to what counts as an embed, could land on one platform and not the\n * other and silently misroute revenue.\n */\n\n/** A beneficiary route as it appears in `comment_options`. */\nexport interface ThreeSpeakBeneficiaryRoute {\n account: string;\n weight: number;\n src?: string;\n}\n\nexport const THREESPEAK_BENEFICIARY_ACCOUNT = \"threespeakfund\";\n\n/** Beneficiary weight in basis points: 1100 = 11%. */\nexport const THREESPEAK_BENEFICIARY_WEIGHT = 1100;\n\n/**\n * Whether the body embeds a 3Speak video.\n *\n * Matches an actual embed url (e.g. `https://play.3speak.tv/embed?v=user/id`), not a plain\n * text mention of \"3speak.tv/embed\", which would otherwise attach an 11% route to a post that\n * merely talks about 3Speak.\n *\n * `3speak.tv` must be the host, either bare or under dot-delimited subdomains. The previous\n * `[a-z.]*` prefix also matched a lookalike domain such as `fake3speak.tv`, which would have\n * routed 11% of a user's rewards to threespeakfund for a video 3Speak never hosted. Matching\n * is case-insensitive because hostnames are, and a missed match means the route is silently\n * not attached rather than anything failing loudly.\n *\n * Note this requires an `/embed` path segment. The embed url is not built locally, it comes\n * back from 3Speak on upload, so if that shape ever changes this predicate stops recognising\n * it and the route is silently not attached.\n */\nexport function hasThreeSpeakEmbed(body: string): boolean {\n return /https?:\\/\\/([a-z0-9-]+\\.)*3speak\\.tv\\/embed[?/]/i.test(body);\n}\n\n/**\n * Ensures the 3Speak beneficiary is present, at the correct weight, when the body embeds a\n * 3Speak video. Other beneficiaries are preserved and the input is never mutated. Returns the\n * original array reference untouched when there is nothing to change, so callers can use it as\n * a cheap equality check.\n */\nexport function enforceThreeSpeakBeneficiary(\n beneficiaries: T[],\n body: string\n): (T | ThreeSpeakBeneficiaryRoute)[] {\n if (!hasThreeSpeakEmbed(body)) {\n return beneficiaries;\n }\n\n const existing = beneficiaries.find((b) => b.account === THREESPEAK_BENEFICIARY_ACCOUNT);\n\n if (existing && existing.weight === THREESPEAK_BENEFICIARY_WEIGHT) {\n return beneficiaries;\n }\n\n if (existing) {\n return beneficiaries.map((b) =>\n b.account === THREESPEAK_BENEFICIARY_ACCOUNT\n ? { ...b, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n : b\n );\n }\n\n return [\n ...beneficiaries,\n { account: THREESPEAK_BENEFICIARY_ACCOUNT, weight: THREESPEAK_BENEFICIARY_WEIGHT }\n ];\n}\n\n/** Whether a beneficiary entry is the 3Speak route, which the UI locks from editing. */\nexport function isThreeSpeakBeneficiary(account: string): boolean {\n return account === THREESPEAK_BENEFICIARY_ACCOUNT;\n}\n","export * from \"./get-account-token-query-options\";\nexport * from \"./get-account-videos-query-options\";\n","export * from \"./get-decode-memo-query-options\";\n","import { queryOptions } from \"@tanstack/react-query\";\nimport hs from \"hivesigner\";\n\nexport function getDecodeMemoQueryOptions(\n username: string,\n memo: string,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"hivesigner\", \"decode-memo\", username],\n queryFn: async () => {\n if (accessToken) {\n const hsClient = new hs.Client({\n accessToken,\n });\n return hsClient.decode(memo);\n }\n },\n });\n}\n","import * as queries from \"./queries\";\n\nconst HiveSignerIntegration = {\n queries,\n};\n\nexport { HiveSignerIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveSignerIntegration } from \"../../hivesigner\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\n\nexport function getAccountTokenQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"authenticate\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n const memoQueryOptions =\n HiveSignerIntegration.queries.getDecodeMemoQueryOptions(\n username,\n (await response.json()).memo,\n accessToken\n );\n await getQueryClient().prefetchQuery(memoQueryOptions);\n const { memoDecoded } = getQueryClient().getQueryData(\n memoQueryOptions.queryKey\n );\n\n return memoDecoded.replace(\"#\", \"\");\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ThreeSpeakVideo } from \"../types\";\nimport { getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { getAccountTokenQueryOptions } from \"./get-account-token-query-options\";\n\nexport function getAccountVideosQueryOptions(\n username: string | undefined,\n accessToken: string | undefined\n) {\n return queryOptions({\n queryKey: [\"integrations\", \"3speak\", \"videos\", username],\n enabled: !!username && !!accessToken,\n queryFn: async () => {\n if (!username || !accessToken) {\n throw new Error(\"[SDK][Integrations][3Speak] – anon user\");\n }\n\n const tokenQueryOptions = getAccountTokenQueryOptions(\n username,\n accessToken\n );\n\n await getQueryClient().prefetchQuery(tokenQueryOptions);\n const token = getQueryClient().getQueryData(tokenQueryOptions.queryKey);\n if (!token) {\n throw new Error(\"[SDK][Integrations][3Speak] – missing account token\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://studio.3speak.tv/mobile/api/my-videos`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n }\n );\n return (await response.json()) as ThreeSpeakVideo[];\n },\n });\n}\n","export * from \"./types\";\nexport * from \"./functions\";\nimport * as queries from \"./queries\";\n\nconst ThreeSpeakIntegration = {\n queries,\n};\n\nexport { ThreeSpeakIntegration };\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getBoundFetch } from \"@/modules/core\";\n\nexport function getHivePoshLinksQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"integrations\", \"hiveposh\", \"links\", username],\n retry: false, // Don't retry on user not found errors\n queryFn: async () => {\n try {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `https://hiveposh.com/api/v0/linked-accounts/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n // Handle 400 error when user is not registered on HivePosh\n if (response.status === 400) {\n const errorData = await response.json().catch(() => ({}));\n // Silently return null for \"User Not Connected\" errors\n if (errorData?.message === \"User Not Connected\") {\n return null;\n }\n }\n\n if (!response.ok) {\n return null;\n }\n\n const data = await response.json();\n\n return {\n twitter: {\n username: data.twitter_username,\n profile: data.twitter_profile,\n },\n reddit: {\n username: data.reddit_username,\n profile: data.reddit_profile,\n },\n } satisfies Record<\n \"twitter\" | \"reddit\",\n { username: string; profile: string }\n >;\n } catch (err) {\n // Silently handle all HivePosh API errors\n return null;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\n\nexport interface StatsResponse {\n results: [\n {\n metrics: number[];\n dimensions: string[];\n },\n ];\n query: {\n site_id: string;\n metrics: string[];\n date_range: string[];\n filters: string[];\n };\n}\ninterface UseStatsQueryOptions {\n url: string;\n dimensions?: string[];\n metrics?: string[];\n /**\n * Which dimension the `url` is matched against. `event:page` (default) matches\n * any visit that viewed the page; `visit:entry_page` matches only visits that\n * landed on it. The API route validates this against an allow-list.\n */\n filterBy?: \"event:page\" | \"visit:entry_page\";\n /**\n * Plausible `date_range`. Pass a tuple `[from, to]` (ISO `YYYY-MM-DD`) to scope\n * the query — e.g. a post's creation date through today. Scoping is essential:\n * ClickHouse orders events by `(site_id, toDate(timestamp), …)` and partitions\n * by month, so a bounded range prunes to a few granules instead of scanning the\n * whole history. Omitting it falls back to the route default (`\"all\"`), which on\n * a high-traffic site is a multi-second full scan. Plausible also accepts the\n * relative keywords `\"day\"`, `\"7d\"`, `\"30d\"`, `\"all\"`.\n */\n dateRange?: string | [string, string];\n enabled?: boolean;\n}\n\nexport function getStatsQueryOptions({\n url,\n dimensions = [],\n metrics = [\"visitors\", \"pageviews\", \"visit_duration\"],\n filterBy = \"event:page\",\n dateRange,\n enabled = true,\n}: UseStatsQueryOptions) {\n return queryOptions({\n queryKey: [\"integrations\", \"plausible\", url, dimensions, metrics, filterBy, dateRange],\n queryFn: async () => {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(`${CONFIG.privateApiHost}/api/stats`, {\n method: \"POST\",\n body: JSON.stringify({\n metrics,\n url: encodeURIComponent(url),\n dimensions,\n filterBy,\n // Only forward a range when set, so the route keeps owning the default.\n ...(dateRange ? { date_range: dateRange } : {}),\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n // The proxy route returns 5xx (504/502) with an empty body on a Plausible\n // timeout/transport error, and Plausible itself can return a 4xx error JSON.\n // Without this guard those parse into an object with no `results`, and the UI\n // silently renders 0 — indistinguishable from a real zero. Throw instead so\n // React Query surfaces the error and retries.\n if (!response.ok) {\n throw new Error(`Failed to fetch Plausible stats: ${response.status}`);\n }\n\n return (await response.json()) as StatsResponse;\n },\n enabled: !!url && enabled,\n // Stats queries are now date-scoped and cheap; a single retry rides out a\n // transient slow scan without re-introducing the all-time pile-up.\n retry: 1,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getRcStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"resource-credits\", \"stats\"],\n queryFn: async () => {\n const response = await callRPC(\"rc_api.get_rc_stats\", {});\n return response.rc_stats;\n },\n });\n}\n","import { callRPC } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getAccountRcQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"resource-credits\", \"account\", username],\n queryFn: async (): Promise => {\n const result = await callRPC(\"rc_api.find_rc_accounts\", {\n accounts: [username],\n });\n return result.rc_accounts;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { RcResourceParams } from \"../types/resource-params\";\n\n/**\n * Curve coefficients and sizing constants used to price resource usage.\n *\n * These only change at a hardfork, so the entry is kept for the session:\n * `gcTime: Infinity` is the one value that schedules no gc timer at all, so it\n * does not hold a request's query cache open on the server the way a long\n * finite window would.\n *\n * `staleTime` stays bounded on purpose. Making it infinite too would mean a\n * long-lived session keeps pricing with pre-hardfork coefficients forever,\n * quietly producing wrong RC estimates with no way to recover short of a\n * reload. A day is long enough that this is effectively never refetched, and\n * short enough that a hardfork corrects itself.\n */\nexport function getRcResourceParamsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.resourceCredits.resourceParams(),\n staleTime: 24 * 60 * 60 * 1000,\n gcTime: Infinity,\n queryFn: async () => (await callRPC(\"rc_api.get_resource_params\", {})) as RcResourceParams\n });\n}\n","/** Shape returned by `rc_api.get_resource_params`. Numbers arrive as strings. */\nexport interface RcPriceCurveParams {\n coeff_a: string | number;\n coeff_b: string | number;\n shift: string | number;\n}\n\nexport interface RcResourceDynamicsParams {\n resource_unit: string | number;\n budget_per_time_unit: string | number;\n pool_eq: string | number;\n max_pool_size: string | number;\n}\n\nexport interface RcResourceParamEntry {\n resource_dynamics_params: RcResourceDynamicsParams;\n price_curve_params: RcPriceCurveParams;\n}\n\n/**\n * Per-operation and per-transaction sizing constants. Only the members this\n * module needs are declared; the node returns many more.\n */\nexport interface RcSizeInfo {\n resource_state_bytes: {\n comment_base_size: number;\n comment_permlink_char_size: number;\n comment_beneficiaries_member_size: number;\n transaction_base_size: number;\n [key: string]: number;\n };\n resource_execution_time: {\n comment_time: number;\n comment_options_time: number;\n transaction_time: number;\n verify_authority_time: number;\n [key: string]: number;\n };\n [key: string]: Record;\n}\n\nexport interface RcResourceParams {\n resource_params: Record;\n size_info: RcSizeInfo;\n}\n\n/**\n * Resource order is consensus-defined (`HIVE_RC_NUM_RESOURCE_TYPES`) and the\n * `pool`, `share` and `budget` arrays in rc_stats are indexed by it.\n */\nexport const RC_RESOURCE_NAMES = [\n \"resource_history_bytes\",\n \"resource_new_accounts\",\n \"resource_market_bytes\",\n \"resource_state_bytes\",\n \"resource_execution_time\"\n] as const;\n\nexport type RcResourceName = (typeof RC_RESOURCE_NAMES)[number];\n\nexport interface RcCostBreakdown {\n resource: RcResourceName;\n usage: number;\n cost: number;\n}\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * Operations the RC pre-check can estimate. Mirrors the keys exposed by\n * `rc_api.get_rc_stats` (see {@link RcStats}[\"ops\"]).\n */\nexport type RcPrecheckOperation = keyof RcStats[\"ops\"];\n\nexport interface RcPrecheckInput {\n /** From `getAccountRcQueryOptions(username)` -> rcAccounts[0]. */\n rcAccount: RCAccount | null | undefined;\n /** From `getRcStatsQueryOptions()`. */\n rcStats: RcStats | null | undefined;\n /** The operation the user is about to broadcast. */\n operation: RcPrecheckOperation;\n /**\n * Safety multiplier applied to the average operation cost when deciding\n * whether the broadcast will \"likely fail\". Actual on-chain cost varies with\n * network load, so we keep headroom. Defaults to 1.2.\n */\n buffer?: number;\n}\n\nexport interface RcPrecheckResult {\n /** Both inputs were available, so the estimate is meaningful. */\n ready: boolean;\n /** Current RC mana of the account. */\n currentMana: number;\n /** Maximum RC mana of the account. */\n maxMana: number;\n /** Average RC cost of the operation. */\n avgCost: number;\n /** Average cost padded by `buffer`. */\n estimatedCost: number;\n /** `currentMana` is below the padded estimate -> broadcast likely fails. */\n willLikelyFail: boolean;\n /** RC shortfall vs the padded estimate (0 when not failing). */\n deficit: number;\n /** Roughly how many such operations the account can still afford. */\n remaining: number;\n}\n\nconst EMPTY: RcPrecheckResult = {\n ready: false,\n currentMana: 0,\n maxMana: 0,\n avgCost: 0,\n estimatedCost: 0,\n willLikelyFail: false,\n deficit: 0,\n remaining: 0,\n};\n\n/**\n * Pure, client-side estimate of whether an account has enough Resource Credits\n * to broadcast an operation, used to warn the user BEFORE they submit instead\n * of failing afterwards with the chain's \"Please wait to transact\" error.\n *\n * It is intentionally approximate: it uses the network-wide average cost from\n * `rc_api.get_rc_stats`, padded by a buffer. Treat `willLikelyFail` as a hint,\n * never a hard gate - the publish/comment/vote action must stay non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n operation,\n buffer = 1.2,\n}: RcPrecheckInput): RcPrecheckResult {\n if (!rcAccount || !rcStats?.ops) {\n return EMPTY;\n }\n\n const { current_mana: currentMana, max_mana: maxMana } = calculateRCMana(rcAccount);\n const avgCost = Number(rcStats.ops[operation]?.avg_cost ?? 0);\n\n if (!(avgCost > 0)) {\n return { ...EMPTY, ready: true, currentMana, maxMana };\n }\n\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = avgCost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / avgCost),\n };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcPriceCurveParams,\n type RcResourceName,\n type RcResourceParams,\n type RcSizeInfo\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\n\n/**\n * What the chain actually charges for publishing a comment, rather than the\n * network-average cost of an average comment.\n *\n * The average is a poor guide for posts: it is dominated by short replies,\n * while a long post is charged mostly on `history_bytes`, which is the\n * serialized transaction size. A real case: an account holding 21.3B RC was\n * told it could afford 17 posts, then a 46,620-byte post was rejected needing\n * 23.3B RC, more than that account's entire maximum.\n *\n * This is a direct port of `resource_credits::compute_cost` and the\n * `comment_operation` arm of `count_resources` from hive, so it tracks what\n * the node does instead of approximating it. Verified against a real\n * rejection: usage reproduces exactly and total cost lands within 0.3%, the\n * residual coming from `share` being published rounded to four digits.\n */\n\n/**\n * Fixed transaction header: ref_block_num(2) + ref_block_prefix(4) +\n * expiration(4) + the extensions varint(1).\n */\nconst TRANSACTION_HEADER_BYTES = 11;\n/** Compact signature, 65 bytes each. */\nconst SIGNATURE_BYTES = 65;\n/** asset = amount int64(8) + precision(1) + symbol(7). */\nconst ASSET_BYTES = 16;\n\nconst big = (v: string | number): bigint => BigInt(typeof v === \"string\" ? v : Math.trunc(v));\n\n/**\n * Port of `resource_credits::compute_cost` (libraries/chain/rc/rc_utility.cpp).\n *\n * BigInt is required, not stylistic: `coeff_a` is ~1.05e19, well past\n * Number.MAX_SAFE_INTEGER, so float arithmetic loses the low bits and the\n * result drifts.\n */\nexport function computeResourceCost(\n curve: RcPriceCurveParams,\n pool: number,\n resourceCount: number,\n regenShare: number\n): number {\n if (resourceCount <= 0 || regenShare <= 0) {\n return 0;\n }\n\n const coeffA = big(curve.coeff_a);\n const coeffB = big(curve.coeff_b);\n const shift = big(curve.shift);\n\n // The node shifts before multiplying by the resource count, because\n // regen * coeff_a already risks overflowing 128 bits. Order matters.\n let num = (big(regenShare) * coeffA) >> shift;\n num += 1n;\n num *= big(resourceCount);\n\n const denom = coeffB + (pool > 0 ? big(pool) : 0n);\n if (denom === 0n) {\n return 0;\n }\n\n return Number(num / denom + 1n);\n}\n\nexport interface CommentResourceUsageInput {\n /** Byte length of the serialized transaction. */\n transactionBytes: number;\n permlinkLength: number;\n /** Signatures on the transaction; a normal post carries one. */\n signatures?: number;\n /**\n * Beneficiary count on the companion comment_options, when publish appends\n * one. The chain counts resources for every operation in the transaction,\n * not just the comment.\n */\n beneficiaries?: number;\n hasCommentOptions?: boolean;\n}\n\n/**\n * Port of the `comment_operation` and `comment_options_operation` arms of\n * `count_resources` (libraries/chain/rc/resource_count.cpp). Reproduces the\n * chain's numbers exactly, see the spec.\n */\nexport function countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength,\n signatures = 1,\n beneficiaries = 0,\n hasCommentOptions = false\n }: CommentResourceUsageInput,\n sizeInfo: RcSizeInfo\n): Record {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n resource_history_bytes: transactionBytes,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes:\n state.comment_base_size +\n state.comment_permlink_char_size * permlinkLength +\n state.transaction_base_size +\n // comment_payout_beneficiaries is visited from comment_options\n state.comment_beneficiaries_member_size * beneficiaries,\n resource_execution_time:\n exec.comment_time +\n exec.transaction_time +\n exec.verify_authority_time * signatures +\n (hasCommentOptions ? exec.comment_options_time : 0)\n };\n}\n\nexport interface CommentLike {\n author: string;\n permlink: string;\n parent_author: string;\n parent_permlink: string;\n title: string;\n body: string;\n json_metadata: string;\n}\n\n\n/** A beneficiary route as it appears in comment_options extensions. */\nexport interface BeneficiaryRoute {\n account: string;\n weight: number;\n}\n\n/**\n * The comment_options operation publish appends when the author sets\n * beneficiaries or a non-default reward split.\n */\nexport interface CommentOptionsLike {\n beneficiaries?: BeneficiaryRoute[];\n}\n\n/** Serialized bytes of one string field: its varint length plus its bytes. */\nconst stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst commentOperationBytes = (op: CommentLike): number =>\n 1 + // operation variant id\n stringFieldBytes(op.parent_author) +\n stringFieldBytes(op.parent_permlink) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n stringFieldBytes(op.title) +\n stringFieldBytes(op.body) +\n stringFieldBytes(op.json_metadata);\n\nconst commentOptionsBytes = (op: CommentLike, options: CommentOptionsLike): number => {\n const beneficiaries = options.beneficiaries ?? [];\n let bytes =\n 1 + // operation variant id\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n ASSET_BYTES + // max_accepted_payout\n 2 + // percent_hbd\n 2; // allow_votes + allow_curation_rewards\n\n bytes += varintByteLength(beneficiaries.length > 0 ? 1 : 0);\n if (beneficiaries.length > 0) {\n bytes += 1 + varintByteLength(beneficiaries.length); // extension variant id + route count\n beneficiaries.forEach((route) => {\n bytes += stringFieldBytes(route.account) + 2; // weight is uint16\n });\n }\n return bytes;\n};\n\nexport interface CommentTransactionInput {\n op: CommentLike;\n /** Present when publish appends comment_options for beneficiaries or rewards. */\n options?: CommentOptionsLike;\n signatures?: number;\n}\n\n/**\n * Serialized size of the transaction that will carry this comment.\n *\n * This models Hive's binary encoding rather than approximating it: a fixed\n * header, one varint-prefixed field per string, and 65 bytes per signature.\n * Verified byte-exact against eight real transactions read back with\n * `get_transaction_hex`, including one carrying comment_options.\n */\nexport function estimateCommentTransactionBytes({\n op,\n options,\n signatures = 1\n}: CommentTransactionInput): number {\n const operations = [commentOperationBytes(op)];\n if (options) {\n operations.push(commentOptionsBytes(op, options));\n }\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(operations.length) +\n operations.reduce((sum, bytes) => sum + bytes, 0) +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\nexport interface EstimateCommentRcCostInput {\n op: CommentLike;\n /** Companion comment_options, when the author set beneficiaries or rewards. */\n options?: CommentOptionsLike;\n rcParams: RcResourceParams | undefined;\n rcStats: Pick | undefined;\n signatures?: number;\n}\n\nexport interface CommentRcCostEstimate {\n /** False until both queries have resolved; callers must not warn on this. */\n ready: boolean;\n cost: number;\n transactionBytes: number;\n breakdown: RcCostBreakdown[];\n}\n\nconst EMPTY: CommentRcCostEstimate = {\n ready: false,\n cost: 0,\n transactionBytes: 0,\n breakdown: []\n};\n\n/** Total RC the chain will charge to broadcast this comment. */\nexport function estimateCommentRcCost({\n op,\n options,\n rcParams,\n rcStats,\n signatures = 1\n}: EstimateCommentRcCostInput): CommentRcCostEstimate {\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats?.pool || !rcStats.share) {\n return EMPTY;\n }\n\n const transactionBytes = estimateCommentTransactionBytes({ op, options, signatures });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: utf8ByteLength(op.permlink),\n signatures,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n\n const regen = Number(rcStats.regen);\n let cost = 0;\n const breakdown: RcCostBreakdown[] = [];\n\n RC_RESOURCE_NAMES.forEach((name, index) => {\n const entry = rcParams.resource_params[name];\n const pool = Number(rcStats.pool[index] ?? 0);\n const share = Number(rcStats.share[index] ?? 0);\n if (!entry || share <= 0) {\n return;\n }\n\n // `usage` is scaled by the resource unit before pricing. It is 1 for the\n // resources a comment touches, but market bytes and new accounts are not.\n const scaled = usage[name] * Number(entry.resource_dynamics_params.resource_unit ?? 1);\n // rc_stats publishes `share` as weight/divisor scaled to 10,000. Kept in\n // BigInt: regen is ~2.4e12 and the product is past the safe-integer range\n // for larger shares.\n const regenShare = Number((BigInt(regen) * BigInt(share)) / 10000n);\n const resourceCost = computeResourceCost(entry.price_curve_params, pool, scaled, regenShare);\n\n cost += resourceCost;\n breakdown.push({ resource: name, usage: scaled, cost: resourceCost });\n });\n\n return { ready: true, cost, transactionBytes, breakdown };\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { GetGameStatus } from \"../types\";\n\nexport function getGameStatusCheckQueryOptions(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\"\n) {\n return queryOptions({\n queryKey: [\"games\", \"status-check\", gameType, username],\n enabled: !!username && !!code,\n queryFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/get-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()) as GetGameStatus;\n },\n });\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { GameClaim } from \"../types\";\nimport { useRecordActivity } from \"@/modules/analytics/mutations\";\n\nexport function useGameClaim(\n username: string | undefined,\n code: string | undefined,\n gameType: \"spin\",\n key: string\n) {\n const { mutateAsync: recordActivity } = useRecordActivity(\n username,\n \"spin-rolled\"\n );\n\n return useMutation({\n mutationKey: [\"games\", \"post\", gameType, username],\n mutationFn: async () => {\n if (!username || !code) {\n throw new Error(\"[SDK][Games] – missing auth\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/post-game\",\n {\n method: \"POST\",\n body: JSON.stringify({\n game_type: gameType,\n code,\n key,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (await response.json()) as GameClaim;\n },\n onSuccess() {\n recordActivity();\n },\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { QuestsResponse } from \"../types\";\n\n/**\n * Read-only daily/weekly/monthly quest progress for a user. Aggregates the existing\n * points ledger (no auth required — same sensitivity as `/private-api/points`).\n */\nexport function getQuestsQueryOptions(username: string | undefined) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.quests.status(name),\n enabled: !!name,\n queryFn: async () => {\n if (!name) {\n throw new Error(\"[SDK][Quests] – username wasn't provided\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/quests\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ username: name }),\n },\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch quests: ${response.status}`);\n }\n\n return (await response.json()) as QuestsResponse;\n },\n staleTime: 30000,\n refetchOnMount: true,\n });\n}\n","/**\n * Shared quest catalog — the single source of truth for which quests exist, their\n * encouraging goals, copy keys and icon hints. Lives in the SDK so the web and mobile\n * clients render an identical, harmonized set. The backend (`/private-api/quests`)\n * returns raw progress + the reward `cap`; this catalog layers the presentation.\n *\n * `goal` is an *encouraging, reachable* daily target and is intentionally independent of\n * the backend reward `cap` (the point at which the existing reward decays to ~0). It is\n * tunable here without any backend change.\n */\n\nexport type QuestTier = \"daily\" | \"weekly\" | \"monthly\";\n\nexport interface QuestCatalogEntry {\n id: string;\n tier: QuestTier;\n /** encouraging, reachable target for the period (tunable, not the reward cap) */\n goal: number;\n /** i18n key suffix; clients resolve e.g. `quests..title` / `.desc` */\n i18nKey: string;\n /** semantic icon hint; each client maps it to its own icon set */\n icon: string;\n}\n\nexport const QUEST_CATALOG: QuestCatalogEntry[] = [\n // Daily\n { id: \"checkin\", tier: \"daily\", goal: 1, i18nKey: \"checkin\", icon: \"check-circle\" },\n { id: \"post\", tier: \"daily\", goal: 1, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"daily\", goal: 3, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"daily\", goal: 10, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"daily\", goal: 1, i18nKey: \"reblog\", icon: \"repeat\" },\n { id: \"spin\", tier: \"daily\", goal: 1, i18nKey: \"spin\", icon: \"gift\" },\n // Weekly\n { id: \"post\", tier: \"weekly\", goal: 5, i18nKey: \"post\", icon: \"pencil\" },\n { id: \"comment\", tier: \"weekly\", goal: 15, i18nKey: \"comment\", icon: \"comment\" },\n { id: \"vote\", tier: \"weekly\", goal: 50, i18nKey: \"vote\", icon: \"chevron-up-circle\" },\n { id: \"reblog\", tier: \"weekly\", goal: 5, i18nKey: \"reblog\", icon: \"repeat\" },\n // Monthly\n { id: \"post\", tier: \"monthly\", goal: 20, i18nKey: \"post\", icon: \"pencil\" },\n];\n\nexport function getQuestCatalogEntry(tier: QuestTier, id: string) {\n return QUEST_CATALOG.find((q) => q.tier === tier && q.id === id);\n}\n\n/**\n * Shortest body that earns points and counts toward the post/comment quests.\n *\n * MIRRORS the ePoints `CONTENT_MIN_LENGTH` - the backend is the source of truth and\n * rejects anything at or below it, silently. This exists so a client can say so in the\n * composer instead of leaving the user to wonder why their reply never counted.\n */\nexport const QUEST_MIN_CONTENT_LENGTH = 25;\n\n/**\n * The length the backend actually measures. URLs are stripped first, so a reply that is\n * nothing but an image link measures as empty however long it looks. Mirrors the\n * `http(s)://\\S+` strip in the ePoints verifier, including the absence of any trimming.\n *\n * Counts code points, not UTF-16 code units, because the backend measures with Python's\n * `len` on a str. `String.length` would score an astral character (most emoji) as 2,\n * so a reply of 13 emoji would look like 26 here and 13 there: the client would promise\n * points the backend then refuses, which is the exact confusion this is meant to end.\n */\nexport function measureQuestContentLength(body: string | null | undefined): number {\n return Array.from((body ?? \"\").replace(/https?:\\/\\/\\S+/g, \"\")).length;\n}\n\n/**\n * Whether a post or comment body is long enough to earn points and quest credit.\n * Strictly greater than the minimum, matching the backend comparison.\n */\nexport function earnsQuestContentCredit(body: string | null | undefined): boolean {\n return measureQuestContentLength(body) > QUEST_MIN_CONTENT_LENGTH;\n}\n\n// Streak Freeze display config. MIRRORS the ePoints constants\n// (STREAK_FREEZE_PRICE / STREAK_FREEZE_MAX_OWNED) — the server is the source of truth\n// and validates every purchase; these drive the label + button state only, so a drift\n// here never over-charges (the buy is priced server-side).\nexport const STREAK_FREEZE_PRICE = 300;\nexport const STREAK_FREEZE_MAX_OWNED = 2;\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { StreakFreezeBuyResult } from \"../types\";\n\n/** A fresh idempotency key per purchase; guarded for runtimes without crypto.randomUUID. */\nfunction genIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * POST a single streak-freeze purchase. Throws on a non-2xx with the server's\n * `.status` + parsed `.data` attached so the caller can branch on 402 (insufficient)\n * / 409 (max owned). Exported for unit testing; the hook below wraps it.\n */\nexport async function buyStreakFreezeRequest(\n code: string\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/streak-freeze/buy\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, idempotency_key: genIdempotencyKey() }),\n }\n );\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to buy streak freeze: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as StreakFreezeBuyResult;\n}\n\n/**\n * Buy one streak freeze (a Points-only sink). The server debits Points, caps owned\n * inventory, and is idempotent per key. On success the quests + points caches are\n * invalidated so the owned count and balance refresh. A 402 (insufficient) / 409 (max\n * owned) is rethrown with `.status` + `.data` so the caller can route to a Points top-up.\n */\nexport function useBuyStreakFreeze(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"streak-freeze\", \"buy\", name],\n mutationFn: async () => {\n if (!name || !code) {\n throw new Error(\"[SDK][StreakFreeze] – missing auth\");\n }\n return buyStreakFreezeRequest(code);\n },\n onSuccess() {\n // Balance only changes on a successful debit.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.points._prefix(name) });\n }\n },\n onSettled() {\n // Refresh freezes_owned on success AND error: a 409 (max owned) means the\n // client's count is stale, and without this the \"Protect streak\" button would\n // never hide and the user could keep re-triggering 409s.\n if (name) {\n queryClient.invalidateQueries({ queryKey: QueryKeys.quests.status(name) });\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for subscribing to a community.\n */\nexport interface SubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for subscribing to a community.\n *\n * This mutation broadcasts a subscribe operation to the Hive blockchain,\n * adding the community to the user's subscription list.\n *\n * @param username - The username subscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"subscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const subscribeMutation = useSubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Subscribe to a community\n * subscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useSubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"subscribe\"],\n username,\n ({ community }) => [\n buildSubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUnsubscribeOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for unsubscribing from a community.\n */\nexport interface UnsubscribeCommunityPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n}\n\n/**\n * React Query mutation hook for unsubscribing from a community.\n *\n * This mutation broadcasts an unsubscribe operation to the Hive blockchain,\n * removing the community from the user's subscription list.\n *\n * @param username - The username unsubscribing (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates subscriptions cache to show updated subscription list\n * - Invalidates community cache to refetch updated subscriber count\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"unsubscribe\", {\"community\": \"hive-123456\"}]\n * - Authority: Posting key\n *\n * @example\n * ```typescript\n * const unsubscribeMutation = useUnsubscribeCommunity(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Unsubscribe from a community\n * unsubscribeMutation.mutate({\n * community: 'hive-123456'\n * });\n * ```\n */\nexport function useUnsubscribeCommunity(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"unsubscribe\"],\n username,\n ({ community }) => [\n buildUnsubscribeOp(username!, community)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.subscriptions(username!),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n QueryKeys.communities.context(username!, variables.community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildMutePostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for muting/unmuting a post in a community.\n */\nexport interface MutePostPayload {\n /** Community name (e.g., \"hive-123456\") */\n community: string;\n /** Post author */\n author: string;\n /** Post permlink */\n permlink: string;\n /** Mute reason/notes (required even for unmute) */\n notes: string;\n /** True to mute, false to unmute */\n mute: boolean;\n}\n\n/**\n * React Query mutation hook for muting/unmuting posts in a community.\n *\n * This mutation broadcasts a custom_json operation to mute (or unmute)\n * a post within a community. Only community moderators/admins can mute posts.\n *\n * @param username - The username performing the mute (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community posts cache to hide muted content\n * - Invalidates post cache to update mute status\n * - Invalidates feed cache to remove muted posts from feeds\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"mutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Action (unmute): [\"unmutePost\", {\"community\": \"hive-123456\", \"account\": \"author\", \"permlink\": \"post\", \"notes\": \"reason\"}]\n * - Authority: Posting key\n *\n * **Mute vs Unmute:**\n * - mute: true - Mutes the post (hides from community feed)\n * - mute: false - Unmutes the post (restores to community feed)\n *\n * **Permission:**\n * - Only community moderators and admins can mute/unmute posts\n * - Attempting to mute without permission will fail with an error\n *\n * @example\n * ```typescript\n * const mutePostMutation = useMutePost(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Mute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Violates community guidelines',\n * mute: true\n * });\n *\n * // Unmute a post\n * mutePostMutation.mutate({\n * community: 'hive-123456',\n * author: 'alice',\n * permlink: 'my-post',\n * notes: 'Resolved after editing',\n * mute: false\n * });\n * ```\n */\nexport function useMutePost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"mutePost\"],\n username,\n ({ community, author, permlink, notes, mute }) => [\n buildMutePostOp(username!, community, author, permlink, notes, mute)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n const queriesToInvalidate: any[] = [\n // Invalidate specific post cache to update mute status\n QueryKeys.posts.entry(`/@${variables.author}/${variables.permlink}`),\n // Invalidate community data\n [\"community\", \"single\", variables.community],\n // Invalidate community feed/posts (matches all sort orders, limits, observers)\n {\n predicate: (query: any) => {\n const key = query.queryKey;\n return (\n Array.isArray(key) &&\n key[0] === \"posts\" &&\n key[1] === \"posts-ranked\" &&\n key[3] === variables.community\n );\n }\n }\n ];\n await auth.adapter.invalidateQueries(queriesToInvalidate);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'sync' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetRoleOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community, CommunityTeam } from \"../types\";\n\n/**\n * Payload for setting a user's role in a community.\n */\nexport interface SetCommunityRolePayload {\n /** Account to set role for */\n account: string;\n /** Role name (e.g., \"admin\", \"mod\", \"member\", \"guest\") */\n role: string;\n}\n\n/**\n * React Query mutation hook for setting a user's role in a community.\n *\n * This mutation broadcasts a setRole operation to the Hive blockchain,\n * updating the role of a community member. Only users with appropriate\n * permissions (community owner/admin) can set roles.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username setting the role (required for broadcast, must have permission)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated team member list\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"setRole\", {\"community\": \"hive-123456\", \"account\": \"user\", \"role\": \"mod\"}]\n * - Authority: Posting key\n *\n * **Role Types:**\n * - \"owner\" - Community owner (full permissions)\n * - \"admin\" - Administrator (can manage settings and team)\n * - \"mod\" - Moderator (can mute posts/users)\n * - \"member\" - Regular member (no special permissions)\n * - \"guest\" - Remove user from team (empty string also works)\n *\n * @example\n * ```typescript\n * const setRoleMutation = useSetCommunityRole('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Set a user as moderator\n * setRoleMutation.mutate({\n * account: 'alice',\n * role: 'mod'\n * });\n *\n * // Remove a user from the team\n * setRoleMutation.mutate({\n * account: 'bob',\n * role: 'guest'\n * });\n * ```\n */\nexport function useSetCommunityRole(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"set-role\", community],\n username,\n ({ account, role }) => [\n buildSetRoleOp(username!, community, account, role)\n ],\n async (_result: any, variables) => {\n // Optimistic team update in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n const team: CommunityTeam = [...(prev.team ?? [])];\n const idx = team.findIndex(([name]) => name === variables.account);\n if (idx >= 0) {\n team[idx] = [team[idx][0], variables.role, team[idx][2] ?? \"\"];\n } else {\n team.push([variables.account, variables.role, \"\"]);\n }\n return { ...prev, team };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries + context for affected user\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)],\n QueryKeys.communities.context(variables.account, community)\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, getQueryClient, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildUpdateCommunityOp, type CommunityProps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Community } from \"../types\";\n\n/**\n * Payload for updating community properties.\n * Matches the CommunityProps interface from builders.\n */\nexport type UpdateCommunityPayload = CommunityProps;\n\n/**\n * React Query mutation hook for updating community properties.\n *\n * This mutation broadcasts an updateProps operation to the Hive blockchain,\n * modifying the community's metadata and settings. Only community admins\n * can update community properties.\n *\n * @param community - Community name (e.g., \"hive-123456\")\n * @param username - The username updating the community (required for broadcast, must be admin)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to refetch updated properties\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"community\"\n * - Action: [\"updateProps\", {\"community\": \"hive-123456\", \"props\": {...}}]\n * - Authority: Posting key\n *\n * **Properties:**\n * - title - Community display title\n * - about - Short description/tagline\n * - lang - Primary language code (e.g., \"en\")\n * - description - Full community description (markdown supported)\n * - flag_text - Custom text shown when flagging posts\n * - is_nsfw - Whether community contains NSFW content\n *\n * @example\n * ```typescript\n * const updateMutation = useUpdateCommunity('hive-123456', username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Update community properties\n * updateMutation.mutate({\n * title: 'My Awesome Community',\n * about: 'A place for awesome people',\n * lang: 'en',\n * description: '# Welcome\\nThis is our community description',\n * flag_text: 'Please explain why this content violates our rules',\n * is_nsfw: false\n * });\n * ```\n */\nexport function useUpdateCommunity(\n community: string,\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"update\", community],\n username,\n (props) => [\n buildUpdateCommunityOp(username!, community, props)\n ],\n async (_result: any, variables) => {\n // Optimistic property merge in community cache\n // Query key is [\"community\",\"single\",name,observer] — observer varies, so use predicate\n const qc = getQueryClient();\n qc.setQueriesData(\n { queryKey: QueryKeys.communities.singlePrefix(community) },\n (prev) => {\n if (!prev) return prev;\n return { ...prev, ...(variables as unknown as Partial) };\n }\n );\n\n // Cache invalidation — prefix-match all community single queries\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n [...QueryKeys.communities.singlePrefix(community)]\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildCommunityRegistrationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for community rewards registration.\n */\nexport interface CommunityRewardsRegisterPayload {\n /** Community account name (usually the community creator's account) */\n name: string;\n}\n\n/**\n * React Query mutation hook for registering to receive community rewards.\n *\n * This mutation broadcasts a custom_json operation to register a community\n * account to receive Ecency Points rewards for community activity.\n *\n * @param username - The username registering for community rewards (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates community cache to update registration status\n * - Invalidates points balance to reflect potential initial rewards\n *\n * **Operation Details:**\n * - Uses custom_json operation with id \"ecency_registration\"\n * - JSON: {\"name\": \"communityname\"}\n * - Authority: Active key (required for registration)\n *\n * **Purpose:**\n * - Enables communities to receive Ecency Points for activity\n * - One-time registration per community\n * - Can only be done by the community owner/creator\n *\n * @example\n * ```typescript\n * const registerMutation = useRegisterCommunityRewards(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Register community for rewards\n * registerMutation.mutate({\n * name: 'hive-123456'\n * });\n * ```\n */\nexport function useRegisterCommunityRewards(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"registerRewards\"],\n username,\n ({ name }) => [\n buildCommunityRegistrationOp(name)\n ],\n async (_result: any, variables) => {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n // Invalidate community cache to update registration status\n [...QueryKeys.communities.singlePrefix(variables.name)],\n // Invalidate points balance\n [...QueryKeys.points._prefix(username!)],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildPinPostOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface PinPostPayload {\n community: string;\n account: string;\n permlink: string;\n pin: boolean;\n}\n\nexport function usePinPost(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"communities\", \"pin-post\"],\n username,\n ({ community, account, permlink, pin }) => [\n buildPinPostOp(username!, community, account, permlink, pin)\n ],\n async (_result, variables) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.posts.entry(`/@${variables.account}/${variables.permlink}`),\n [...QueryKeys.communities.singlePrefix(variables.community)],\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { Communities } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunitiesQueryOptions(\n sort: string,\n query?: string,\n limit = 100,\n observer: string | undefined = undefined,\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.list(sort, query ?? \"\", limit),\n enabled,\n queryFn: async () => {\n const response = await callRPC(\"bridge.list_communities\", {\n last: \"\",\n limit,\n sort: sort === \"hot\" ? \"rank\" : sort,\n query: query ? query : null,\n observer,\n });\n return (\n response\n ? sort === \"hot\"\n ? response.sort(() => Math.random() - 0.5)\n : response\n : []\n ) as Communities;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { CommunityRole } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getCommunityContextQueryOptions(\n username: string | undefined,\n communityName: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.context(username!, communityName!),\n enabled: !!username && !!communityName,\n queryFn: async () => {\n const response = await callRPC(\"bridge.get_community_context\", {\n account: username,\n name: communityName,\n });\n\n return {\n role: response?.role ?? \"guest\",\n subscribed: response?.subscribed ?? false,\n } satisfies {\n role: CommunityRole;\n subscribed: boolean;\n };\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Community } from \"../types/community\";\nimport { getCommunity } from \"@/modules/bridge\";\nimport { QueryKeys } from \"@/modules/core\";\n\nexport function getCommunityQueryOptions(\n name: string | undefined,\n observer: string | undefined = \"\",\n enabled = true\n) {\n return queryOptions({\n queryKey: QueryKeys.communities.single(name, observer),\n enabled: enabled && !!name,\n queryFn: async () => getCommunity(name ?? \"\", observer) as Promise,\n });\n}\n","import {\n InfiniteData,\n infiniteQueryOptions,\n queryOptions\n} from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { Subscription } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * hivemind caps `bridge.list_subscribers` at 100 rows per call, regardless of a\n * larger requested limit.\n */\nexport const SUBSCRIBERS_PAGE_SIZE = 100;\n\ntype SubscribersPage = Subscription[];\ntype SubscribersCursor = string | null;\n\n/**\n * Fetches one page of subscribers.\n *\n * `last` is omitted on the first page rather than passed as an empty string:\n * hivemind reads `\"\"` as a real cursor positioned before the first account and\n * returns zero rows.\n */\nasync function fetchSubscribersPage(\n communityName: string,\n last: SubscribersCursor\n): Promise {\n const response = await callRPC(\"bridge.list_subscribers\", {\n community: communityName,\n limit: SUBSCRIBERS_PAGE_SIZE,\n ...(last ? { last } : {})\n });\n return (response as Subscription[] | null) ?? [];\n}\n\n/**\n * Get the first page of subscribers for a community.\n *\n * @deprecated Returns at most {@link SUBSCRIBERS_PAGE_SIZE} subscribers, which\n * for most communities is a small fraction of the total while looking like the\n * complete list. Prefer {@link getCommunitySubscribersInfiniteQueryOptions}\n * unless a single page is genuinely all that is wanted.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersQueryOptions(communityName: string) {\n return queryOptions({\n queryKey: QueryKeys.communities.subscribers(communityName),\n queryFn: async () => fetchSubscribersPage(communityName, null),\n staleTime: 60000\n });\n}\n\n/**\n * Get all subscribers for a community, paged with hivemind's `last` cursor.\n *\n * @param communityName - The community name (e.g., \"hive-123456\")\n */\nexport function getCommunitySubscribersInfiniteQueryOptions(\n communityName: string\n) {\n return infiniteQueryOptions<\n SubscribersPage,\n Error,\n InfiniteData,\n string[],\n SubscribersCursor\n >({\n queryKey: QueryKeys.communities.subscribersInfinite(communityName),\n initialPageParam: null as SubscribersCursor,\n queryFn: async ({ pageParam }: { pageParam: SubscribersCursor }) =>\n fetchSubscribersPage(communityName, pageParam),\n // The cursor is the previous page's last account name. A short page is the\n // end of the list.\n getNextPageParam: (lastPage: SubscribersPage): SubscribersCursor =>\n lastPage?.length >= SUBSCRIBERS_PAGE_SIZE\n ? lastPage[lastPage.length - 1]?.[0] ?? null\n : null,\n staleTime: 60000\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { AccountNotification } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\ntype NotifPage = AccountNotification[];\ntype NotifCursor = number | null;\n\n/**\n * Get account notifications for a community (bridge API)\n *\n * @param account - The account/community name\n * @param limit - Number of notifications per page\n */\nexport function getAccountNotificationsInfiniteQueryOptions(\n account: string,\n limit: number\n) {\n return infiniteQueryOptions<\n NotifPage,\n Error,\n InfiniteData,\n (string | number)[],\n NotifCursor\n >({\n queryKey: QueryKeys.communities.accountNotifications(account, limit),\n initialPageParam: null as NotifCursor,\n\n // Errors are deliberately not caught. Returning [] on failure made an RPC\n // outage indistinguishable from an empty log: `isError` never became true,\n // so consumers rendered \"no activity\" for a failed request, and a failed\n // page produced no cursor and silently ended pagination. Let React Query\n // own the error so `isError` and retry behave normally.\n queryFn: async ({ pageParam }: { pageParam: NotifCursor }) => {\n const response = await callRPC(\"bridge.account_notifications\", {\n account,\n limit,\n last_id: pageParam ?? undefined,\n });\n return (response as AccountNotification[] | null) ?? [];\n },\n\n // A short page is the end of the log. Keying on \"empty\" alone would also\n // treat a truncated page as the end.\n getNextPageParam: (lastPage: NotifPage): NotifCursor =>\n lastPage?.length >= limit ? lastPage[lastPage.length - 1].id : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { RewardedCommunity } from \"../types/rewarded-community\";\n\nexport function getRewardedCommunitiesQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.communities.rewarded(),\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/rewarded-communities\",\n {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch rewarded communities: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","export enum ROLES {\n OWNER = \"owner\",\n ADMIN = \"admin\",\n MOD = \"mod\",\n MEMBER = \"member\",\n GUEST = \"guest\",\n MUTED = \"muted\",\n}\n\nexport const roleMap: Record = {\n [ROLES.OWNER]: [\n ROLES.ADMIN,\n ROLES.MOD,\n ROLES.MEMBER,\n ROLES.GUEST,\n ROLES.MUTED,\n ],\n [ROLES.ADMIN]: [ROLES.MOD, ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n [ROLES.MOD]: [ROLES.MEMBER, ROLES.GUEST, ROLES.MUTED],\n};\n\nexport type CommunityTeam = Array>;\nexport type CommunityRole = (typeof ROLES)[keyof typeof ROLES]; // \"owner\" | \"member\" | ...\nexport type CommunityType = \"Topic\" | \"Journal\" | \"Council\";\n\nexport interface Community {\n about: string;\n admins?: string[];\n avatar_url: string;\n created_at: string;\n description: string;\n flag_text: string;\n id: number;\n is_nsfw: boolean;\n lang: string;\n name: string;\n num_authors: number;\n num_pending: number;\n subscribers: number;\n sum_pending: number;\n settings?: any;\n team: CommunityTeam;\n title: string;\n type_id: number;\n}\n\nexport type Communities = Community[];\n","import { CommunityRole, CommunityType, ROLES } from \"../types\";\n\nexport function getCommunityType(name: string, type_id: number): CommunityType {\n if (name.startsWith(\"hive-3\") || type_id === 3) return \"Council\";\n if (name.startsWith(\"hive-2\") || type_id === 2) return \"Journal\";\n return \"Topic\";\n}\n\nexport function getCommunityPermissions({\n communityType,\n userRole,\n subscribed,\n}: {\n communityType: CommunityType;\n userRole: CommunityRole;\n subscribed: boolean;\n}) {\n const canPost = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n if (communityType === \"Topic\") return true;\n\n // Journal & Council\n return [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD, ROLES.MEMBER].includes(\n userRole\n );\n })();\n\n const canComment = (() => {\n if (userRole === ROLES.MUTED) return false;\n\n switch (communityType) {\n case \"Topic\":\n return true;\n case \"Journal\":\n return userRole !== ROLES.GUEST || subscribed;\n case \"Council\":\n return canPost;\n }\n })();\n\n const isModerator = [ROLES.OWNER, ROLES.ADMIN, ROLES.MOD].includes(userRole);\n\n return {\n canPost,\n canComment,\n isModerator,\n };\n}\n","import { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\nexport function getNotificationsUnreadCountQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.unreadCount(activeUsername),\n queryFn: async () => {\n if (!code) {\n return 0;\n }\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/notifications/unread`,\n {\n method: \"POST\",\n body: JSON.stringify({ code }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n const data = (await response.json()) as { count: number };\n return data.count;\n },\n enabled: !!activeUsername && !!code,\n initialData: 0,\n refetchInterval: 60000,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { NotificationFilter } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { ApiNotification } from \"../types\";\n\nexport function getNotificationsInfiniteQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n filter: NotificationFilter | undefined = undefined\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.notifications.list(activeUsername, filter),\n queryFn: async ({ pageParam }) => {\n if (!code) {\n return [];\n }\n const data = {\n code,\n filter,\n since: pageParam,\n user: undefined,\n };\n\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/notifications\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(data),\n }\n );\n\n if (!response.ok) {\n return [];\n }\n\n try {\n return (await response.json()) as ApiNotification[];\n } catch {\n return [];\n }\n },\n enabled: !!activeUsername && !!code,\n // No initialData here: an empty seed counts as fresh for the whole staleTime,\n // so consumers that only read `data` would render an empty list with no fetch.\n initialPageParam: \"\",\n getNextPageParam: (lastPage) => lastPage?.[lastPage.length - 1]?.id ?? \"\",\n refetchOnMount: true,\n });\n}\n","export enum NotificationFilter {\n VOTES = \"rvotes\",\n MENTIONS = \"mentions\",\n FAVORITES = \"nfavorites\",\n BOOKMARKS = \"nbookmarks\",\n FOLLOWS = \"follows\",\n REPLIES = \"replies\",\n REBLOGS = \"reblogs\",\n TRANSFERS = \"transfers\",\n DELEGATIONS = \"delegations\",\n PAYOUTS = \"payouts\",\n SCHEDULED_PUBLISHED = \"scheduled_published\",\n // Filter path is plural while the notification `type` string is singular\n // (`account_update`) - enotify routes on the plural form.\n ACCOUNT_UPDATES = \"account_updates\",\n WEEKLY_EARNINGS = \"weekly_earnings\",\n}\n","// Values are enotify's ACTIVITY_MAIN_TYPE_* ints and are validated server-side at\n// device registration, so they must match enotify constants.py exactly. Note payouts\n// is 19: the original 16 is commented out upstream and must not be reused.\nexport enum NotifyTypes {\n VOTE = 1,\n MENTION = 2,\n FOLLOW = 3,\n COMMENT = 4,\n RE_BLOG = 5,\n TRANSFERS = 6,\n DELEGATIONS = 10,\n FAVORITES = 13,\n BOOKMARKS = 15,\n PAYOUTS = 19,\n ACCOUNT_UPDATE = 20,\n WEEKLY_EARNINGS = 21,\n SCHEDULED_PUBLISHED = 22,\n ALLOW_NOTIFY = \"ALLOW_NOTIFY\",\n}\n\nexport const ALL_NOTIFY_TYPES = [\n NotifyTypes.VOTE,\n NotifyTypes.MENTION,\n NotifyTypes.FOLLOW,\n NotifyTypes.COMMENT,\n NotifyTypes.RE_BLOG,\n NotifyTypes.TRANSFERS,\n NotifyTypes.DELEGATIONS,\n NotifyTypes.FAVORITES,\n NotifyTypes.BOOKMARKS,\n NotifyTypes.PAYOUTS,\n NotifyTypes.ACCOUNT_UPDATE,\n NotifyTypes.WEEKLY_EARNINGS,\n NotifyTypes.SCHEDULED_PUBLISHED,\n] as const;\n\nexport enum NotificationViewType {\n ALL = \"All\",\n UNREAD = \"Unread\",\n READ = \"Read\",\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ApiNotificationSetting } from \"../types\";\nimport { ALL_NOTIFY_TYPES } from \"../enums\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\n\nexport function getNotificationsSettingsQueryOptions(\n activeUsername: string | undefined,\n code: string | undefined,\n initialMuted?: boolean\n) {\n return queryOptions({\n queryKey: QueryKeys.notifications.settings(activeUsername),\n queryFn: async () => {\n let token = activeUsername + \"-web\";\n if (!code) {\n throw new Error(\"Missing access token\");\n }\n const response = await fetch(\n CONFIG.privateApiHost + \"/private-api/detail-device\",\n {\n body: JSON.stringify({\n code,\n username: activeUsername,\n token,\n }),\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n if (!response.ok) {\n throw new Error(`Failed to fetch notification settings: ${response.status}`);\n }\n return response.json() as Promise;\n },\n enabled: !!activeUsername && !!code,\n refetchOnMount: false,\n initialData: () => {\n return {\n status: 0,\n system: \"web\",\n allows_notify: 0,\n notify_types: initialMuted ? [] : ([...ALL_NOTIFY_TYPES] as number[]),\n } as ApiNotificationSetting;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Announcement } from \"../types/announcement\";\n\nexport function getAnnouncementsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.notifications.announcements(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/announcements\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch announcements: ${response.status}`);\n }\n\n const data = await response.json() as Announcement[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys } from \"@/modules/core\";\nimport { Spotlight } from \"../types/spotlight\";\n\n// `_accessToken` is accepted for call-site parity with mobile (which passes one) but is\n// intentionally unused: the spotlights endpoint is anonymous and only filters by date window.\nexport function getSpotlightsQueryOptions(_accessToken?: string) {\n return queryOptions({\n queryKey: QueryKeys.notifications.spotlights(),\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/spotlights\", {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch spotlights: ${response.status}`);\n }\n\n const data = (await response.json()) as Spotlight[];\n return data || [];\n },\n staleTime: 3_600_000,\n });\n}\n","import { useMutation, QueryKey, InfiniteData } from \"@tanstack/react-query\";\nimport { getQueryClient, QueryKeys } from \"@/modules/core\";\nimport { markNotifications } from \"@/modules/private-api/requests\";\nimport { ApiNotification } from \"../types\";\n\ntype NotificationPage = ApiNotification[];\ntype InfiniteNotificationData = InfiniteData;\n\nfunction markNotificationRead(item: ApiNotification, id?: string): ApiNotification {\n return {\n ...item,\n read: (!id || id === item.id ? 1 : item.read) as 0 | 1,\n };\n}\n\nfunction isInfiniteData(data: unknown): data is InfiniteNotificationData {\n return (\n typeof data === \"object\" &&\n data !== null &&\n \"pages\" in data &&\n \"pageParams\" in data &&\n Array.isArray((data as InfiniteNotificationData).pages)\n );\n}\n\n/**\n * Hook to mark notifications as read with optimistic updates\n *\n * @param username - Current user's username\n * @param code - Access token for authentication\n * @param onSuccess - Optional callback on successful mutation, receives unread count\n * @param onError - Optional callback on error\n *\n * @returns Mutation hook that accepts { id?: string }\n *\n * @example\n * ```typescript\n * const markAsRead = useMarkNotificationsRead(username, code);\n *\n * // Mark specific notification\n * markAsRead.mutate({ id: \"notification-id\" });\n *\n * // Mark all notifications (omit id)\n * markAsRead.mutate({});\n * ```\n */\nexport function useMarkNotificationsRead(\n username: string | undefined,\n code: string | undefined,\n onSuccess?: (unreadCount?: number) => void,\n onError?: (e: Error) => void\n) {\n const queryClient = getQueryClient();\n\n return useMutation({\n mutationKey: [\"notifications\", \"mark-read\", username],\n\n mutationFn: async ({ id }: { id?: string }) => {\n if (!username || !code) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[SDK][Notifications] – missing auth for markNotifications\");\n }\n return;\n }\n return markNotifications(code, id);\n },\n\n // Optimistic update: Immediately mark notifications as read in cache\n onMutate: async ({ id }: { id?: string }) => {\n // Skip optimistic updates when auth is not available\n if (!username || !code) {\n return { previousData: [] };\n }\n\n // Cancel any outgoing refetches to prevent overwriting optimistic update\n await queryClient.cancelQueries({ queryKey: QueryKeys.notifications._prefix });\n\n // Snapshot current state for rollback\n const previousData: Array<[QueryKey, unknown]> = [];\n\n // Update infinite notification list queries (pages structure)\n const infiniteQueries = queryClient.getQueriesData({\n queryKey: QueryKeys.notifications._prefix,\n predicate: (query) => {\n const data = query.state.data;\n return isInfiniteData(data);\n },\n });\n\n infiniteQueries.forEach(([queryKey, data]) => {\n if (data && isInfiniteData(data)) {\n previousData.push([queryKey, data]);\n\n const updatedData: InfiniteNotificationData = {\n ...data,\n pages: data.pages.map((page) =>\n page.map((item) => markNotificationRead(item, id))\n ),\n };\n\n queryClient.setQueryData(queryKey, updatedData);\n }\n });\n\n // Optimistically decrement unread count\n const unreadKey = QueryKeys.notifications.unreadCount(username);\n const currentUnread = queryClient.getQueryData(unreadKey);\n if (typeof currentUnread === \"number\" && currentUnread > 0) {\n previousData.push([unreadKey, currentUnread]);\n\n if (!id) {\n // Mark all: set to 0\n queryClient.setQueryData(unreadKey, 0);\n } else {\n // Mark single: only decrement if the notification is currently unread\n const isUnread = infiniteQueries.some(([, d]) =>\n d?.pages.some((page) =>\n page.some((item) => item.id === id && item.read === 0)\n )\n );\n if (isUnread) {\n queryClient.setQueryData(unreadKey, currentUnread - 1);\n }\n }\n }\n\n // Return context for rollback\n return { previousData };\n },\n\n onSuccess: (response) => {\n // Extract unread count from response if available\n const unreadCount = typeof response === \"object\" && response !== null\n ? (response as { unread?: number }).unread\n : undefined;\n\n // Update unread count cache with server value\n if (typeof unreadCount === \"number\") {\n queryClient.setQueryData(\n QueryKeys.notifications.unreadCount(username),\n unreadCount\n );\n }\n\n onSuccess?.(unreadCount);\n },\n\n // Rollback optimistic update on error\n onError: (error, _variables, context) => {\n // Restore previous state\n if (context?.previousData) {\n context.previousData.forEach(([queryKey, data]) => {\n queryClient.setQueryData(queryKey, data);\n });\n }\n\n onError?.(error as Error);\n },\n\n // Always refetch after mutation settles\n onSettled: () => {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.notifications._prefix,\n });\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildSetLastReadOps } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface SetLastReadPayload {\n date?: string;\n}\n\nexport function useSetLastRead(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"notifications\", \"set-last-read\"],\n username,\n ({ date }) => buildSetLastReadOps(username!, date),\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.notifications.unreadCount(username),\n ]);\n }\n },\n auth,\n 'posting',\n { broadcastMode: broadcastMode ?? 'async' }\n );\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get a single proposal by ID\n */\nexport function getProposalQueryOptions(id: number) {\n return queryOptions({\n queryKey: [\"proposals\", \"proposal\", id],\n queryFn: async () => {\n const r = await callRPC(\"condenser_api.find_proposals\", [[id]]);\n const proposal = r[0];\n\n // Determine proposal status based on dates\n if (new Date(proposal.start_date) < new Date() && new Date(proposal.end_date) >= new Date()) {\n proposal.status = \"active\";\n } else if (new Date(proposal.end_date) < new Date()) {\n proposal.status = \"expired\";\n } else {\n proposal.status = \"inactive\";\n }\n\n return proposal as Proposal;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { Proposal } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get all proposals, sorted with expired proposals at the end\n */\nexport function getProposalsQueryOptions() {\n return queryOptions({\n queryKey: [\"proposals\", \"list\"],\n queryFn: async () => {\n const response = (await callRPC(\"database_api.list_proposals\", {\n start: [-1],\n limit: 500,\n order: \"by_total_votes\",\n order_direction: \"descending\",\n status: \"all\",\n })) as { proposals: Proposal[] };\n\n const proposals = response.proposals;\n const expired = proposals.filter((x) => x.status === \"expired\");\n const others = proposals.filter((x) => x.status !== \"expired\");\n\n return [...others, ...expired];\n },\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { FullAccount } from \"@/modules/accounts\";\nimport { parseAccounts } from \"@/modules/accounts/utils\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n// One page = array of enriched vote rows\nexport type ProposalVoteRow = {\n id: number;\n voter: string;\n voterAccount: FullAccount;\n};\n\ntype Cursor = string; // we paginate by last voter name\n\n/**\n * Get proposal votes with pagination and enriched voter account data\n *\n * @param proposalId - The proposal ID\n * @param voter - Starting voter for pagination\n * @param limit - Number of votes per page\n */\nexport function getProposalVotesInfiniteQueryOptions(\n proposalId: number,\n voter: string,\n limit: number\n) {\n return infiniteQueryOptions<\n ProposalVoteRow[],\n Error,\n InfiniteData,\n (string | number)[],\n Cursor\n >({\n queryKey: [\"proposals\", \"votes\", proposalId, voter, limit],\n initialPageParam: voter as Cursor,\n refetchOnMount: true,\n staleTime: 0, // Always refetch on mount\n\n queryFn: async ({ pageParam }: { pageParam: Cursor }) => {\n const startParam = pageParam ?? voter;\n\n const response = (await callRPC(\"condenser_api.list_proposal_votes\", [\n [proposalId, startParam],\n limit,\n \"by_proposal_voter\",\n ])) as ProposalVote[];\n\n const list = response\n .filter((x) => x.proposal?.proposal_id === proposalId)\n .map((x) => ({ id: x.id, voter: x.voter }));\n\n const rawAccounts = await callRPC(\"condenser_api.get_accounts\", [list.map((l) => l.voter)]);\n const accounts = parseAccounts(rawAccounts);\n\n const page: ProposalVoteRow[] = list.map((i) => ({\n ...i,\n voterAccount: accounts.find((a) => i.voter === a.name)!,\n }));\n\n return page;\n },\n\n getNextPageParam: (lastPage: ProposalVoteRow[]): Cursor | undefined => {\n const last = lastPage?.[lastPage.length - 1];\n return last?.voter ?? undefined;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ProposalVote } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Fetches ALL proposal votes for a specific user in a single query.\n * Much more efficient than querying each proposal individually.\n * Uses \"by_voter_proposal\" order to get all votes by a user.\n */\nexport function getUserProposalVotesQueryOptions(voter: string) {\n return queryOptions({\n queryKey: [\"proposals\", \"votes\", \"by-user\", voter],\n enabled: !!voter && voter !== \"\",\n staleTime: 60 * 1000, // Cache for 1 minute\n queryFn: async () => {\n if (!voter || voter === \"\") {\n return [];\n }\n\n const response = (await callRPC(\"database_api.list_proposal_votes\", {\n start: [voter],\n limit: 1000,\n order: \"by_voter_proposal\",\n order_direction: \"ascending\",\n status: \"votable\",\n })) as { proposal_votes: ProposalVote[] };\n\n // Filter to only this user's votes (API might return votes after this user alphabetically)\n const userVotes = (response.proposal_votes || []).filter((vote) => vote.voter === voter);\n\n return userVotes;\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting on proposals.\n */\nexport interface ProposalVotePayload {\n /** Array of proposal IDs to vote on */\n proposalIds: number[];\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting on Hive proposals.\n *\n * This mutation broadcasts an update_proposal_votes operation to vote on\n * one or more proposals in the Hive Decentralized Fund (HDF).\n *\n * @param username - The username voting on proposals (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Records activity (type 150) if adapter.recordActivity is available\n * - Invalidates proposal list cache to show updated vote status\n * - Invalidates voter's proposal votes cache\n *\n * **Multiple Proposals:**\n * - You can vote on multiple proposals in a single transaction\n * - All proposals receive the same vote (approve or disapprove)\n * - Proposal IDs are integers, not strings\n *\n * **Vote Types:**\n * - approve: true - Vote in favor of the proposal(s)\n * - approve: false - Remove your vote from the proposal(s)\n *\n * @example\n * ```typescript\n * const proposalVoteMutation = useProposalVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Approve a single proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: true\n * });\n *\n * // Approve multiple proposals\n * proposalVoteMutation.mutate({\n * proposalIds: [123, 124, 125],\n * approve: true\n * });\n *\n * // Remove vote from a proposal\n * proposalVoteMutation.mutate({\n * proposalIds: [123],\n * approve: false\n * });\n * ```\n */\nexport function useProposalVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"vote\"],\n username,\n ({ proposalIds, approve }) => [\n buildProposalVoteOp(username!, proposalIds, approve)\n ],\n async (result: any) => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Activity tracking (fire-and-forget — non-critical, shouldn't block mutation completion)\n // Async broadcasts return BroadcastResult ({ tx_id, status }) instead of TransactionConfirmation,\n // so fall back to tx_id when id is absent.\n const txId = result?.id ?? result?.tx_id;\n if (auth?.adapter?.recordActivity && txId) {\n auth.adapter.recordActivity(150, txId, result?.block_num).catch((error) => {\n console.debug(\"[SDK][Proposals][useProposalVote] recordActivity failed\", {\n activityType: 150,\n blockNum: result?.block_num,\n transactionId: txId,\n error\n });\n });\n }\n\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.proposals.list(),\n QueryKeys.proposals.votesByUser(username!)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useProposalVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for proposal votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildProposalCreateOp, type ProposalCreatePayload } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport { type ProposalCreatePayload };\n\nexport function useProposalCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"proposals\", \"create\"],\n username,\n (payload) => [\n buildProposalCreateOp(username!, payload)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.proposals.list(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get vesting delegations for an account with infinite scroll support\n *\n * @param username - The account username\n * @param limit - Maximum number of results per page (default: 50)\n */\nexport function getVestingDelegationsQueryOptions(\n username?: string,\n limit = 50\n) {\n return infiniteQueryOptions({\n queryKey: [\"wallet\", \"vesting-delegations\", username, limit],\n initialPageParam: \"\" as string,\n queryFn: async ({ pageParam }: { pageParam: string }) => {\n // Request one extra item on subsequent pages to handle inclusive cursor\n const fetchLimit = pageParam ? limit + 1 : limit;\n\n const result = await callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n pageParam || \"\",\n fetchLimit,\n ]) as DelegatedVestingShare[];\n\n // Filter out duplicate first item on subsequent pages\n // Hive API is inclusive of the 'from' cursor\n if (pageParam && result.length > 0 && result[0]?.delegatee === pageParam) {\n // Return at most limit items after removing the duplicate\n return result.slice(1, limit + 1);\n }\n\n return result;\n },\n getNextPageParam: (lastPage: DelegatedVestingShare[]) => {\n // If we got fewer results than limit, we've reached the end\n if (!lastPage || lastPage.length < limit) {\n return undefined;\n }\n\n // Return the last delegatee as cursor for next page\n const lastDelegation = lastPage[lastPage.length - 1];\n return lastDelegation?.delegatee;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { AccountDelegations } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\n\n/**\n * Account vesting delegations via the HAF balance-api REST endpoint\n * (`/balance-api/accounts/{account-name}/delegations`).\n *\n * Unlike `condenser_api.get_vesting_delegations` (see\n * {@link getHivePowerDelegatesInfiniteQueryOptions}), this returns the\n * complete outgoing AND incoming lists in a single request, with `callREST`\n * handling multi-node failover. `amount` is raw vests (vests * 10^6).\n */\nexport function getAccountDelegationsQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"assets\", \"account-delegations\", username],\n enabled: !!username,\n queryFn: ({ signal }) =>\n callREST(\n \"balance\",\n \"/accounts/{account-name}/delegations\",\n { \"account-name\": username },\n undefined,\n undefined,\n signal\n ) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { VestingDelegationExpiration } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get expiring vesting delegations for an account.\n *\n * When a delegation is removed (set to 0 VESTS), the HP doesn't return\n * immediately — it enters a 5-day cooldown. This query fetches those\n * in-flight expirations so they can be shown alongside active delegations.\n *\n * Uses database_api.find_vesting_delegation_expirations which returns\n * vesting_shares as NAI asset objects ({amount, nai, precision}).\n *\n * @param username - The delegator account username\n */\nexport function getVestingDelegationExpirationsQueryOptions(username?: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"vesting-delegation-expirations\", username],\n queryFn: async () => {\n if (!username) return [];\n const result = await callRPC(\"database_api.find_vesting_delegation_expirations\", { account: username }) as { delegations: VestingDelegationExpiration[] };\n return result.delegations;\n },\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { ConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HBD to HIVE conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CollateralizedConversionRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get collateralized HIVE to HBD conversion requests for an account\n *\n * @param account - The account username\n */\nexport function getCollateralizedConversionRequestsQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"collateralized-conversion-requests\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_collateralized_conversion_requests\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.requestid - b.requestid),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { SavingsWithdrawRequest } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get pending savings withdrawal requests for an account\n *\n * @param account - The account username\n */\nexport function getSavingsWithdrawFromQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"savings-withdraw\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_savings_withdraw_from\", [\n account,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.request_id - b.request_id),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get power down (vesting withdrawal) routes for an account\n *\n * @param account - The account username\n */\nexport function getWithdrawRoutesQueryOptions(account: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"withdraw-routes\", account],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n account,\n \"outgoing\",\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OpenOrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get open market orders for an account\n *\n * @param user - The account username\n */\nexport function getOpenOrdersQueryOptions(user: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"open-orders\", user],\n queryFn: () =>\n callRPC(\"condenser_api.get_open_orders\", [\n user,\n ]) as Promise,\n select: (data) => data.sort((a, b) => a.orderid - b.orderid),\n enabled: !!user,\n });\n}\n","import { InfiniteData, infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { RcDirectDelegation, RcDirectDelegationsResponse } from \"../types/rc-direct-delegation\";\n\ntype RcPage = RcDirectDelegation[];\ntype RcCursor = string | null;\n\n/**\n * Get outgoing RC delegations for an account\n *\n * @param username - Account name to get delegations for\n * @param limit - Number of delegations per page\n */\nexport function getOutgoingRcDelegationsInfiniteQueryOptions(username: string, limit = 100) {\n return infiniteQueryOptions<\n RcPage,\n Error,\n InfiniteData,\n (string | number)[],\n RcCursor\n >({\n queryKey: [\"wallet\", \"outgoing-rc-delegations\", username, limit],\n initialPageParam: null as RcCursor,\n\n queryFn: async ({ pageParam }: { pageParam: RcCursor }) => {\n const response = await callRPC(\"rc_api.list_rc_direct_delegations\", {\n start: [username, pageParam ?? \"\"],\n limit,\n })\n .then((r: any) => r as RcDirectDelegationsResponse);\n\n let delegations: RcDirectDelegation[] = response.rc_direct_delegations || [];\n\n // Filter out the starting delegation when paginating\n if (pageParam) {\n delegations = delegations.filter((delegation) => delegation.to !== pageParam);\n }\n\n return delegations;\n },\n\n getNextPageParam: (lastPage: RcPage): RcCursor =>\n lastPage.length === limit ? lastPage[lastPage.length - 1].to : null,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { IncomingRcResponse } from \"../types\";\n\nexport function getIncomingRcQueryOptions(username: string | undefined) {\n return queryOptions({\n queryKey: [\"wallet\", \"incoming-rc\", username],\n enabled: !!username,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] - Missing username for incoming RC\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n `${CONFIG.privateApiHost}/private-api/received-rc/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch incoming RC: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { ReceivedVestingShare } from \"../types/received-vesting-share\";\n\nexport function getReceivedVestingSharesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"received-vesting-shares\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`\n );\n\n if (!response.ok) {\n throw new Error(`Failed to fetch received vesting shares: ${response.status}`);\n }\n\n const data = (await response.json()) as { list: ReceivedVestingShare[] };\n return data.list;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { RecurrentTransfer } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get recurrent transfers for an account\n *\n * @param username - The account username\n */\nexport function getRecurrentTransfersQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"wallet\", \"recurrent-transfers\", username],\n queryFn: () =>\n callRPC(\"condenser_api.find_recurrent_transfers\", [\n username,\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { ConfigManager } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\n\ntype PortfolioLayer = \"points\" | \"hive\" | \"chain\" | \"engine\";\n\ninterface TokenAction {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface PortfolioWalletItem {\n name: string;\n symbol: string;\n layer: PortfolioLayer;\n balance: number;\n fiatRate: number;\n currency: string;\n precision: number;\n address?: string;\n error?: string;\n pendingRewards?: number;\n pendingRewardsFiat?: number;\n liquid?: number;\n liquidFiat?: number;\n savings?: number;\n savingsFiat?: number;\n staked?: number;\n stakedFiat?: number;\n iconUrl?: string;\n actions?: TokenAction[];\n extraData?: Array<{ dataKey: string; value: any }>;\n apr?: number;\n}\n\nexport interface PortfolioResponse {\n username: string;\n currency?: string;\n wallets: PortfolioWalletItem[];\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n\n return undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n const direct = Number.parseFloat(trimmed);\n if (Number.isFinite(direct)) {\n return direct;\n }\n\n const sanitized = trimmed.replace(/,/g, \"\");\n const match = sanitized.match(/[-+]?\\d+(?:\\.\\d+)?/);\n if (match) {\n const parsed = Number.parseFloat(match[0]);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n }\n\n return undefined;\n}\n\nfunction parseToken(rawToken: unknown): PortfolioWalletItem | undefined {\n if (!rawToken || typeof rawToken !== \"object\") {\n return undefined;\n }\n\n const token = rawToken as Record;\n\n // Portfolio v2 returns well-defined PortfolioItem structure\n return {\n name: normalizeString(token.name) ?? \"\",\n symbol: normalizeString(token.symbol) ?? \"\",\n layer: (normalizeString(token.layer) ?? \"hive\") as PortfolioLayer,\n balance: normalizeNumber(token.balance) ?? 0,\n fiatRate: normalizeNumber(token.fiatRate) ?? 0,\n currency: normalizeString(token.currency) ?? \"usd\",\n precision: normalizeNumber(token.precision) ?? 3,\n address: normalizeString(token.address),\n error: normalizeString(token.error),\n pendingRewards: normalizeNumber(token.pendingRewards),\n pendingRewardsFiat: normalizeNumber(token.pendingRewardsFiat),\n liquid: normalizeNumber(token.liquid),\n liquidFiat: normalizeNumber(token.liquidFiat),\n savings: normalizeNumber(token.savings),\n savingsFiat: normalizeNumber(token.savingsFiat),\n staked: normalizeNumber(token.staked),\n stakedFiat: normalizeNumber(token.stakedFiat),\n iconUrl: normalizeString(token.iconUrl),\n actions: (token.actions ?? []) as TokenAction[],\n extraData: (token.extraData ?? []) as Array<{ dataKey: string; value: any }>,\n apr: normalizeNumber(token.apr),\n };\n}\n\nfunction extractTokens(payload: unknown): unknown[] {\n if (!payload || typeof payload !== \"object\") {\n return [];\n }\n\n const containers = [payload];\n const record = payload as Record;\n if (record.data && typeof record.data === \"object\") {\n containers.push(record.data as Record);\n }\n if (record.result && typeof record.result === \"object\") {\n containers.push(record.result as Record);\n }\n if (record.portfolio && typeof record.portfolio === \"object\") {\n containers.push(record.portfolio as Record);\n }\n\n for (const container of containers) {\n if (Array.isArray(container)) {\n return container;\n }\n\n if (container && typeof container === \"object\") {\n for (const key of [\n \"wallets\",\n \"tokens\",\n \"assets\",\n \"items\",\n \"portfolio\",\n \"balances\",\n ]) {\n const value = (container as Record)[key];\n if (Array.isArray(value)) {\n return value;\n }\n }\n }\n }\n\n return [];\n}\n\nfunction resolveUsername(payload: unknown): string | undefined {\n if (!payload || typeof payload !== \"object\") {\n return undefined;\n }\n\n const record = payload as Record;\n return (\n normalizeString(record.username) ??\n normalizeString(record.name) ??\n normalizeString(record.account)\n );\n}\n\n/**\n * Get portfolio query options for fetching user's wallet balances across all layers\n * @param username - Hive username\n * @param currency - Fiat currency code (default: \"usd\")\n * @param onlyEnabled - Only return enabled tokens (default: true)\n * @returns TanStack Query options for portfolio data\n */\nexport function getPortfolioQueryOptions(\n username: string,\n currency: string = \"usd\",\n onlyEnabled: boolean = true\n) {\n return queryOptions({\n queryKey: [\n \"wallet\",\n \"portfolio\",\n \"v2\",\n username,\n onlyEnabled ? \"only-enabled\" : \"all\",\n currency,\n ],\n enabled: Boolean(username),\n staleTime: 60000,\n refetchInterval: 120000,\n queryFn: async (): Promise => {\n if (!username) {\n throw new Error(\"[SDK][Wallet] – username is required\");\n }\n\n const endpoint = `${ConfigManager.getValidatedBaseUrl()}/wallet-api/portfolio-v2`;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username, onlyEnabled, currency }),\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][Wallet] – Portfolio request failed (${response.status})`\n );\n }\n\n const payload = (await response.json()) as unknown;\n const tokens = extractTokens(payload)\n .map((item) => parseToken(item))\n .filter((item): item is PortfolioWalletItem => Boolean(item))\n // Backend may still emit removed SPK-layer items; drop them defensively\n .filter((item) => (item.layer as string) !== \"spk\");\n\n if (!tokens.length) {\n throw new Error(\n \"[SDK][Wallet] – Portfolio payload contained no tokens\"\n );\n }\n\n return {\n username: resolveUsername(payload) ?? username,\n currency: normalizeString(\n (payload as Record | undefined)?.fiatCurrency ??\n (payload as Record | undefined)?.currency\n )?.toUpperCase(),\n wallets: tokens,\n };\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHiveAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n\n if (!accountData) {\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: 0,\n } satisfies GeneralAssetInfo;\n }\n\n const liquidBalance = parseAsset(accountData.balance).amount;\n const savingsBalance = parseAsset(accountData.savings_balance).amount;\n\n return {\n name: \"HIVE\",\n title: \"Hive\",\n price: Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0,\n accountBalance: liquidBalance + savingsBalance,\n parts: [\n {\n name: \"current\",\n balance: liquidBalance,\n },\n {\n name: \"savings\",\n balance: savingsBalance,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHbdAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hbd\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n\n const price = 1;\n\n if (!accountData) {\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance: 0,\n };\n }\n\n return {\n name: \"HBD\",\n title: \"Hive Dollar\",\n price,\n accountBalance:\n parseAsset(accountData.hbd_balance).amount +\n parseAsset(accountData?.savings_hbd_balance).amount,\n apr: ((dynamicProps?.hbdInterestRate ?? 0) / 100).toFixed(3),\n parts: [\n {\n name: \"current\",\n balance: parseAsset(accountData.hbd_balance).amount,\n },\n {\n name: \"savings\",\n balance: parseAsset(accountData.savings_hbd_balance).amount,\n },\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import type { DynamicProps } from \"@/modules/core\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\nimport { getAccountFullQueryOptions } from \"@/modules/accounts\";\nimport { getDynamicPropsQueryOptions, getQueryClient } from \"@/modules/core\";\nimport type { FullAccount } from \"@/modules/accounts\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { isEmptyDate, parseAsset, vestsToHp } from \"@/modules/core/utils\";\n\nfunction getAPR(dynamicProps: DynamicProps) {\n const initialInflationRate = 9.5;\n const initialBlock = 7000000;\n const decreaseRate = 250000;\n const decreasePercentPerIncrement = 0.01;\n\n const headBlock = dynamicProps.headBlock;\n const deltaBlocks = headBlock - initialBlock;\n const decreaseIncrements = deltaBlocks / decreaseRate;\n\n let currentInflationRate =\n initialInflationRate - decreaseIncrements * decreasePercentPerIncrement;\n\n if (currentInflationRate < 0.95) {\n currentInflationRate = 0.95;\n }\n\n const vestingRewardPercent = dynamicProps.vestingRewardPercent / 10000;\n const virtualSupply = dynamicProps.virtualSupply;\n const totalVestingFunds = dynamicProps.totalVestingFund;\n\n return (\n (virtualSupply * currentInflationRate * vestingRewardPercent) /\n totalVestingFunds\n ).toFixed(3);\n}\n\nexport function getHivePowerAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getDynamicPropsQueryOptions());\n await getQueryClient().prefetchQuery(\n getAccountFullQueryOptions(username)\n );\n\n const dynamicProps = getQueryClient().getQueryData(\n getDynamicPropsQueryOptions().queryKey\n );\n const accountData = getQueryClient().getQueryData(\n getAccountFullQueryOptions(username).queryKey\n );\n\n if (!dynamicProps || !accountData) {\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price: 0,\n accountBalance: 0,\n };\n }\n\n const marketTicker = (await callRPC(\"condenser_api.get_ticker\", [])\n .catch(() => undefined)) as { latest?: string } | undefined;\n\n const marketPrice = Number.parseFloat(marketTicker?.latest ?? \"\");\n const price = Number.isFinite(marketPrice)\n ? marketPrice\n : dynamicProps.base / dynamicProps.quote;\n\n const vestingShares = parseAsset(accountData.vesting_shares).amount;\n const delegatedVests = parseAsset(\n accountData.delegated_vesting_shares\n ).amount;\n const receivedVests = parseAsset(\n accountData.received_vesting_shares\n ).amount;\n const withdrawRateVests = parseAsset(\n accountData.vesting_withdraw_rate\n ).amount;\n const remainingToWithdrawVests = Math.max(\n (Number(accountData.to_withdraw) - Number(accountData.withdrawn)) /\n 1e6,\n 0\n );\n const nextWithdrawalVests = !isEmptyDate(\n accountData.next_vesting_withdrawal\n )\n ? Math.min(withdrawRateVests, remainingToWithdrawVests)\n : 0;\n\n const hpBalance = +vestsToHp(\n vestingShares,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const outgoingDelegationsHp = +vestsToHp(\n delegatedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const incomingDelegationsHp = +vestsToHp(\n receivedVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const pendingPowerDownHp = +vestsToHp(\n remainingToWithdrawVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const nextPowerDownHp = +vestsToHp(\n nextWithdrawalVests,\n dynamicProps.hivePerMVests\n ).toFixed(3);\n const totalBalance = Math.max(hpBalance - pendingPowerDownHp, 0);\n const availableHp = Math.max(hpBalance - outgoingDelegationsHp, 0);\n\n return {\n name: \"HP\",\n title: \"Hive Power\",\n price,\n accountBalance: +totalBalance.toFixed(3),\n apr: getAPR(dynamicProps),\n parts: [\n {\n name: \"hp_balance\",\n balance: hpBalance,\n },\n {\n name: \"available\",\n balance: +availableHp.toFixed(3),\n },\n {\n name: \"outgoing_delegations\",\n balance: outgoingDelegationsHp,\n },\n {\n name: \"incoming_delegations\",\n balance: incomingDelegationsHp,\n },\n ...(pendingPowerDownHp > 0\n ? [\n {\n name: \"pending_power_down\",\n balance: +pendingPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ...(nextPowerDownHp > 0 && nextPowerDownHp !== pendingPowerDownHp\n ? [\n {\n name: \"next_power_down\",\n balance: +nextPowerDownHp.toFixed(3),\n },\n ]\n : []),\n ],\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { utils } from \"../../../hive-tx\";\nimport { HiveOperationGroup } from \"../types\";\nconst ops = utils.operations;\n\nexport const HIVE_ACCOUNT_OPERATION_GROUPS: Record<\n HiveOperationGroup,\n number[]\n> = {\n transfers: [\n ops.transfer,\n ops.transfer_to_savings,\n ops.transfer_from_savings,\n ops.cancel_transfer_from_savings,\n ops.recurrent_transfer,\n ops.fill_recurrent_transfer,\n ops.escrow_transfer,\n ops.fill_recurrent_transfer,\n ],\n \"market-orders\": [\n ops.fill_convert_request,\n ops.fill_order,\n ops.fill_collateralized_convert_request,\n ops.limit_order_create2,\n ops.limit_order_create,\n ops.limit_order_cancel,\n ],\n interests: [ops.interest],\n \"stake-operations\": [\n ops.return_vesting_delegation,\n ops.withdraw_vesting,\n ops.transfer_to_vesting,\n ops.set_withdraw_vesting_route,\n ops.update_proposal_votes,\n ops.fill_vesting_withdraw,\n ops.account_witness_proxy,\n ops.delegate_vesting_shares,\n ],\n rewards: [\n ops.author_reward,\n ops.curation_reward,\n ops.producer_reward,\n ops.claim_reward_balance,\n ops.comment_benefactor_reward,\n ops.liquidity_reward,\n ops.proposal_pay,\n ],\n \"\": [],\n};\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nexport const HIVE_OPERATION_LIST = Object.keys(\n utils.operations\n) as HiveOperationName[];\n","import { utils } from \"../../../hive-tx\";\nimport type { HiveOperationName } from \"../types\";\n\nconst operationOrders = utils.operations as Record<\n HiveOperationName,\n number\n>;\n\nexport const HIVE_OPERATION_ORDERS = operationOrders;\n\nexport const HIVE_OPERATION_NAME_BY_ID: Record =\n Object.entries(operationOrders).reduce((acc, [name, id]) => {\n acc[id] = name as HiveOperationName;\n return acc;\n }, {} as Record);\n","import { callRPC } from \"../../../hive-tx\";\nimport { utils } from \"../../../hive-tx\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { HIVE_ACCOUNT_OPERATION_GROUPS } from \"../consts\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationFilterKey,\n HiveOperationFilterValue,\n HiveOperationGroup,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nconst operationOrders = utils.operations;\n\nfunction isHiveOperationName(value: string): value is HiveOperationName {\n return Object.prototype.hasOwnProperty.call(operationOrders, value);\n}\n\nexport function resolveHiveOperationFilters(filters: HiveOperationFilter): {\n filterKey: HiveOperationFilterKey;\n filterArgs: any[];\n} {\n const rawValues: HiveOperationFilterValue[] = Array.isArray(filters)\n ? filters\n : [filters];\n\n const hasAll = rawValues.includes(\"\" as HiveOperationGroup);\n\n const uniqueValues = Array.from(\n new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined &&\n value !== null &&\n value !== (\"\" as HiveOperationGroup)\n )\n )\n );\n\n const filterKey: HiveOperationFilterKey =\n hasAll || uniqueValues.length === 0\n ? \"all\"\n : uniqueValues\n .map((value) => value.toString())\n .sort()\n .join(\"|\");\n\n const operationIds = new Set();\n\n if (!hasAll) {\n uniqueValues.forEach((value) => {\n if (value in HIVE_ACCOUNT_OPERATION_GROUPS) {\n HIVE_ACCOUNT_OPERATION_GROUPS[value as HiveOperationGroup].forEach(\n (id) => operationIds.add(id)\n );\n return;\n }\n\n if (isHiveOperationName(value)) {\n operationIds.add(operationOrders[value]);\n }\n });\n }\n\n const filterArgs = makeBitMaskFilter(Array.from(operationIds));\n\n return {\n filterKey,\n filterArgs,\n };\n}\n\n/**\n * The filter values the caller passed, minus the \"all\" sentinel. Group aliases are\n * kept as-is: they never equal an operation name, so they simply never match.\n *\n * Used by the per-asset `select` filters so an operation a caller deliberately\n * requested is never silently dropped just because the asset filter has no opinion\n * about it. Passing no filter at all keeps the historical behaviour: the asset's own\n * allow-list decides, and nothing extra leaks in.\n */\nexport function collectRequestedOperations(\n filters: HiveOperationFilter\n): Set {\n const rawValues = Array.isArray(filters) ? filters : [filters];\n return new Set(\n rawValues.filter(\n (value): value is HiveOperationFilterValue =>\n value !== undefined && value !== null && value !== (\"\" as HiveOperationGroup)\n )\n );\n}\n\n/**\n * Cursor for `condenser_api.get_account_history`.\n *\n * A page comes back in ASCENDING `num` order, so the OLDEST entry is at index 0 and\n * walking backwards means `page[0].num - 1`. Reading the LAST entry instead takes the\n * NEWEST row, which advances the window by a single operation per page (a page of 1000\n * overlaps its predecessor by 999) and, once `num` reaches 0, yields -1 — the \"newest\"\n * sentinel `initialPageParam` uses — so the walk restarts at the head of the history and\n * never terminates.\n */\nexport function getNextAccountHistoryPageParam(\n lastPage: HiveTransaction[] | undefined\n): number | undefined {\n if (!lastPage?.length) {\n return undefined;\n }\n\n const oldest = Number(lastPage[0]?.num ?? 0);\n return Number.isFinite(oldest) && oldest > 0 ? oldest - 1 : undefined;\n}\n\n/**\n * The `limit` to request for a given cursor.\n *\n * `condenser_api.get_account_history` asserts `start >= limit - 1`, because `start` is a\n * 0-based index into the account's operation list and the node walks `limit` entries back\n * from it. The cursor above is derived from `num` alone, so the last window before the\n * start of history is necessarily shorter than `limit`, and asking for the full `limit`\n * there fails the assert instead of returning the remaining rows.\n *\n * Narrowing the window to `pageParam + 1` asks for exactly what is left. The `-1`\n * sentinel (\"give me the newest\") is not an index and passes through untouched.\n */\nexport function resolveAccountHistoryLimit(\n pageParam: number,\n limit: number\n): number {\n if (!Number.isFinite(pageParam) || pageParam < 0) {\n return limit;\n }\n\n return Math.min(limit, pageParam + 1);\n}\n\nfunction makeBitMaskFilter(allowedOperations: number[]) {\n let low = 0n;\n let high = 0n;\n\n allowedOperations.forEach((operation) => {\n if (operation < 64) {\n low |= 1n << BigInt(operation);\n } else {\n high |= 1n << BigInt(operation - 64);\n }\n });\n\n return [\n low !== 0n ? low.toString() : null,\n high !== 0n ? high.toString() : null,\n ];\n}\n\nexport function getHiveAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterArgs, filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"transactions\", username, limit, filterKey],\n initialPageParam: -1,\n getNextPageParam: getNextAccountHistoryPageParam,\n\n queryFn: async ({ pageParam }) => {\n const response = await callRPC(\n \"condenser_api.get_account_history\",\n [\n username,\n pageParam,\n resolveAccountHistoryLimit(Number(pageParam), limit),\n ...filterArgs,\n ]\n );\n\n return response.map(\n (x: any) =>\n ({\n num: x[0],\n type: x[1].op[0],\n timestamp: x[1].timestamp,\n trx_id: x[1].trx_id,\n ...x[1].op[1],\n }) satisfies HiveTransaction\n );\n },\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hivePayout = parseAsset(\n (item as AuthorReward).hive_payout\n );\n return hivePayout.amount > 0;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HIVE\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HIVE\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HIVE\"].includes(asset.symbol);\n\n case \"claim_reward_balance\":\n const rewardHive = parseAsset(\n (item as ClaimRewardBalance).reward_hive\n );\n return rewardHive.amount > 0;\n\n case \"curation_reward\":\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // Keep an operation the caller asked for by name. Without this the\n // filter UI advertises every operation while this switch silently\n // discards the ones it has no opinion about, so picking e.g.\n // `fill_transfer_from_savings` returns an empty list. Requests that\n // pass no filter still fall through to `false`, so the unfiltered\n // HIVE view is unchanged.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n HiveOperationName,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n collectRequestedOperations,\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHbdAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n const requestedOperations = collectRequestedOperations(filters);\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\"assets\", \"hbd\", \"transactions\", username, limit, filterKey],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const hbdPayout = parseAsset(\n (item as AuthorReward).hbd_payout\n );\n return hbdPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardHbd = parseAsset(\n (item as ClaimRewardBalance).reward_hbd\n );\n return rewardHbd.amount > 0;\n\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"transfer_to_vesting\":\n case \"recurrent_transfer\":\n return parseAsset(item.amount).symbol === \"HBD\";\n\n case \"transfer_from_savings\" as HiveOperationName:\n // The completed withdrawal carries the same asset as the request that\n // opened it, so it needs the same guard. Without a case of its own it\n // falls to the default below, which has no symbol check.\n case \"fill_transfer_from_savings\" as HiveOperationName:\n return parseAsset((item as any).amount).symbol === \"HBD\";\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"HBD\"].includes(asset.symbol);\n\n case \"cancel_transfer_from_savings\":\n case \"fill_order\":\n case \"limit_order_create\":\n case \"limit_order_cancel\":\n case \"fill_convert_request\":\n case \"fill_collateralized_convert_request\":\n case \"proposal_pay\":\n case \"interest\":\n return true;\n\n case \"limit_order_create2\" as HiveOperationName:\n return true;\n default:\n // See the HIVE options: keep an operation the caller named explicitly,\n // otherwise the filter UI offers operations this switch throws away.\n // Unfiltered requests still fall through to `false`.\n return requestedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { parseAsset } from \"@/modules/core/utils\";\nimport type {\n AuthorReward,\n ClaimRewardBalance,\n HiveOperationFilter,\n} from \"../types\";\nimport type { HiveTransaction } from \"../types\";\nimport {\n getHiveAssetTransactionsQueryOptions,\n resolveHiveOperationFilters,\n} from \"./get-hive-asset-transactions-query-options\";\n\nexport function getHivePowerAssetTransactionsQueryOptions(\n username: string | undefined,\n limit = 20,\n filters: HiveOperationFilter = []\n) {\n const { filterKey } = resolveHiveOperationFilters(filters);\n\n const userSelectedOperations = new Set(\n Array.isArray(filters) ? filters : [filters]\n );\n const hasAllFilter =\n userSelectedOperations.has(\"\" as any) || userSelectedOperations.size === 0;\n\n return infiniteQueryOptions({\n ...getHiveAssetTransactionsQueryOptions(username, limit, filters),\n queryKey: [\n \"assets\",\n \"hive-power\",\n \"transactions\",\n username,\n limit,\n filterKey,\n ],\n select: ({ pages, pageParams }) => ({\n pageParams,\n pages: pages.map((page) =>\n page.filter((item) => {\n switch (item.type) {\n case \"author_reward\":\n case \"comment_benefactor_reward\":\n const vestingPayout = parseAsset(\n (item as AuthorReward).vesting_payout\n );\n return vestingPayout.amount > 0;\n\n case \"claim_reward_balance\":\n const rewardVests = parseAsset(\n (item as ClaimRewardBalance).reward_vests\n );\n return rewardVests.amount > 0;\n\n case \"transfer_to_vesting\":\n return true;\n case \"transfer\":\n case \"transfer_to_savings\":\n case \"recurrent_transfer\":\n return [\"VESTS\", \"HP\"].includes(parseAsset(item.amount).symbol);\n\n case \"fill_recurrent_transfer\":\n const asset = parseAsset(item.amount);\n return [\"VESTS\", \"HP\"].includes(asset.symbol);\n\n case \"curation_reward\":\n case \"withdraw_vesting\":\n case \"delegate_vesting_shares\":\n case \"fill_vesting_withdraw\":\n case \"return_vesting_delegation\":\n case \"producer_reward\":\n case \"set_withdraw_vesting_route\":\n return true;\n default:\n return hasAllFilter || userSelectedOperations.has(item.type);\n }\n })\n ),\n }),\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveMarketMetric } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date): string {\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;\n}\n\nfunction subtractSeconds(date: Date, seconds: number): Date {\n return new Date(date.getTime() - seconds * 1000);\n}\n\nexport function getHiveAssetMetricQueryOptions(bucketSeconds = 86_400) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive\", \"metrics\", bucketSeconds],\n queryFn: async ({ pageParam: [startDate, endDate] }) => {\n const apiData: HiveMarketMetric[] = await callRPC(\"condenser_api.get_market_history\", [bucketSeconds, formatDate(startDate), formatDate(endDate)]\n );\n\n return apiData.map(({ hive, non_hive, open }) => ({\n close: non_hive.close / hive.close,\n open: non_hive.open / hive.open,\n low: non_hive.low / hive.low,\n high: non_hive.high / hive.high,\n volume: hive.volume,\n time: new Date(open),\n }));\n },\n initialPageParam: [\n subtractSeconds(new Date(), Math.max(100 * bucketSeconds, 28_800)),\n new Date(),\n ],\n getNextPageParam: (_, __, [prevStartDate]) => [\n subtractSeconds(prevStartDate, Math.max(100 * bucketSeconds, 28_800)),\n subtractSeconds(prevStartDate, bucketSeconds),\n ],\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { WithdrawRoute } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHiveAssetWithdrawalRoutesQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive\", \"withdrawal-routes\", username],\n queryFn: () =>\n callRPC(\"condenser_api.get_withdraw_routes\", [\n username,\n \"outgoing\",\n ]) as Promise,\n enabled: !!username,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { DelegatedVestingShare } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getHivePowerDelegatesInfiniteQueryOptions(\n username: string,\n limit = 50\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegates\", username],\n enabled: !!username,\n queryFn: () =>\n callRPC(\"condenser_api.get_vesting_delegations\", [\n username,\n \"\",\n limit,\n ]) as Promise,\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { ReceivedVestingShare } from \"../types\";\nimport { parseAsset } from \"@/modules/core/utils\";\n\nexport function getHivePowerDelegatingsQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-power\", \"delegatings\", username],\n queryFn: async () => {\n const response = await fetch(\n CONFIG.privateApiHost + `/private-api/received-vesting/${username}`,\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }\n );\n return (await response.json()).list as ReceivedVestingShare[];\n },\n select: (data) =>\n data.sort(\n (a, b) =>\n parseAsset(b.vesting_shares).amount -\n parseAsset(a.vesting_shares).amount\n ),\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersData } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get the internal HIVE/HBD market order book\n *\n * @param limit - Maximum number of orders to fetch (default: 500)\n */\nexport function getOrderBookQueryOptions(limit = 500) {\n return queryOptions({\n queryKey: [\"market\", \"order-book\", limit],\n queryFn: () =>\n callRPC(\"condenser_api.get_order_book\", [\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market statistics from the blockchain\n */\nexport function getMarketStatisticsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"statistics\"],\n queryFn: () =>\n callRPC(\"condenser_api.get_ticker\", []) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketCandlestickDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get HIVE/HBD market history (candlestick data)\n *\n * @param seconds - Bucket size in seconds\n * @param startDate - Start date for the data\n * @param endDate - End date for the data\n */\nexport function getMarketHistoryQueryOptions(\n seconds: number,\n startDate: Date,\n endDate: Date\n) {\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n return queryOptions({\n queryKey: [\"market\", \"history\", seconds, startDate.getTime(), endDate.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_market_history\", [\n seconds,\n formatDate(startDate),\n formatDate(endDate),\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { HiveHbdStats, MarketCandlestickDataItem, MarketStatistics } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\n/**\n * Get combined HIVE/HBD statistics including price, 24h change, and volume\n */\nexport function getHiveHbdStatsQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"hive-hbd-stats\"],\n queryFn: async () => {\n // Get current market statistics\n const stats = (await callRPC(\"condenser_api.get_ticker\", [])) as MarketStatistics;\n\n // Get 24h market history\n const now = new Date();\n const oneDayAgo = new Date(now.getTime() - 86400000); // 24 hours ago\n\n const formatDate = (date: Date) => {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n };\n\n const dayChange = (await callRPC(\"condenser_api.get_market_history\", [86400, formatDate(oneDayAgo), formatDate(now)]\n )) as MarketCandlestickDataItem[];\n\n // Calculate stats\n const result: HiveHbdStats = {\n price: +stats.latest,\n close: dayChange[0] ? dayChange[0].non_hive.open / dayChange[0].hive.open : 0,\n high: dayChange[0] ? dayChange[0].non_hive.high / dayChange[0].hive.high : 0,\n low: dayChange[0] ? dayChange[0].non_hive.low / dayChange[0].hive.low : 0,\n percent: dayChange[0]\n ? 100 - ((dayChange[0].non_hive.open / dayChange[0].hive.open) * 100) / +stats.latest\n : 0,\n totalFromAsset: stats.hive_volume.split(\" \")[0],\n totalToAsset: stats.hbd_volume.split(\" \")[0],\n };\n\n return result;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { MarketData } from \"../types\";\nimport { getBoundFetch } from \"@/modules/core\";\n\n/**\n * Get market chart data from CoinGecko API\n *\n * @param coin - Coin ID (e.g., \"hive\", \"bitcoin\")\n * @param vsCurrency - Currency to compare against (e.g., \"usd\", \"eur\")\n * @param fromTs - From timestamp (Unix timestamp in seconds)\n * @param toTs - To timestamp (Unix timestamp in seconds)\n */\nexport function getMarketDataQueryOptions(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n) {\n return queryOptions({\n queryKey: [\"market\", \"data\", coin, vsCurrency, fromTs, toTs],\n queryFn: async ({ signal }) => {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n\n const response = await fetchApi(url, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch market data: ${response.status}`);\n }\n\n return response.json() as Promise;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { OrdersDataItem } from \"../types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nfunction formatDate(date: Date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/, \"\");\n}\n\nexport function getTradeHistoryQueryOptions(\n limit = 1000,\n startDate?: Date,\n endDate?: Date\n) {\n const end = endDate ?? new Date();\n const start =\n startDate ?? new Date(end.getTime() - 10 * 60 * 60 * 1000);\n\n return queryOptions({\n queryKey: [\"market\", \"trade-history\", limit, start.getTime(), end.getTime()],\n queryFn: () =>\n callRPC(\"condenser_api.get_trade_history\", [\n formatDate(start),\n formatDate(end),\n limit,\n ]) as Promise,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface FeedHistoryItem {\n id: number;\n current_median_history: {\n base: string;\n quote: string;\n };\n market_median_history: {\n base: string;\n quote: string;\n };\n current_min_history: {\n base: string;\n quote: string;\n };\n current_max_history: {\n base: string;\n quote: string;\n };\n price_history: Array<{\n base: string;\n quote: string;\n }>;\n}\n\n/**\n * Get feed history from the blockchain\n * Returns price feed history including median prices\n */\nexport function getFeedHistoryQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"feed-history\"],\n queryFn: async () => {\n try {\n const feedHistory = await callRPC(\"condenser_api.get_feed_history\", []);\n return feedHistory as FeedHistoryItem;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport interface MedianHistoryPrice {\n base: string;\n quote: string;\n}\n\n/**\n * Get current median history price from the blockchain\n * Returns the current median price for HIVE/HBD conversion\n */\nexport function getCurrentMedianHistoryPriceQueryOptions() {\n return queryOptions({\n queryKey: [\"market\", \"current-median-history-price\"],\n queryFn: async () => {\n try {\n const price = await callRPC(\"condenser_api.get_current_median_history_price\", []);\n return price as MedianHistoryPrice;\n } catch (error) {\n throw error;\n }\n },\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCreateOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCreatePayload {\n amountToSell: string;\n minToReceive: string;\n fillOrKill: boolean;\n expiration: string;\n orderId: number;\n}\n\nexport function useLimitOrderCreate(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-create\"],\n username,\n (payload) => [\n buildLimitOrderCreateOp(\n username!,\n payload.amountToSell,\n payload.minToReceive,\n payload.fillOrKill,\n payload.expiration,\n payload.orderId\n )\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildLimitOrderCancelOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface LimitOrderCancelPayload {\n orderId: number;\n}\n\nexport function useLimitOrderCancel(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"market\", \"limit-order-cancel\"],\n username,\n ({ orderId }) => [\n buildLimitOrderCancelOp(username!, orderId)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.wallet.openOrders(username!),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { MarketData } from \"./types\";\nimport { CurrencyRates } from \"@/modules/private-api/types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nasync function parseJsonResponse(response: Response): Promise {\n const data = (await response.json()) as T;\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n return data;\n}\n\nexport async function getMarketData(\n coin: string,\n vsCurrency: string,\n fromTs: string,\n toTs: string\n): Promise {\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/coins/${coin}/market_chart/range?vs_currency=${vsCurrency}&from=${fromTs}&to=${toTs}`;\n const response = await fetchApi(url);\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRate(cur: string): Promise {\n if (cur === \"hbd\") {\n return 1;\n }\n\n const fetchApi = getBoundFetch();\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${cur}`;\n const response = await fetchApi(url);\n const data = await parseJsonResponse<{ hive_dollar: Record }>(response);\n return data.hive_dollar[cur];\n}\n\nexport async function getCurrencyTokenRate(currency: string, token: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost +\n `/private-api/market-data/${currency === \"hbd\" ? \"usd\" : currency}/${token}`\n );\n\n return parseJsonResponse(response);\n}\n\nexport async function getCurrencyRates(): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/market-data/latest\");\n return parseJsonResponse(response);\n}\n\nexport async function getHivePrice(): Promise<{ hive: { usd: number } }> {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n \"https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd\"\n );\n return parseJsonResponse<{ hive: { usd: number } }>(response);\n}\n","import { ConfigManager, getBoundFetch } from \"@/modules/core\";\nimport type { HiveEngineOpenOrder } from \"./types\";\n\ntype EngineOrderBookEntry = {\n txId: string;\n timestamp: number;\n account: string;\n symbol: string;\n quantity: string;\n price: string;\n tokensLocked?: string;\n};\n\nconst ENGINE_RPC_HEADERS = { \"Content-type\": \"application/json\" };\n\nasync function engineRpc(payload: Record): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(`${baseUrl}/private-api/engine-api`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: ENGINE_RPC_HEADERS,\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – request failed with ${response.status}`\n );\n }\n\n const data = (await response.json()) as { result: T };\n return data.result;\n}\n\nasync function engineRpcSafe(\n payload: Record,\n fallback: T\n): Promise {\n try {\n return await engineRpc(payload);\n } catch (e) {\n return fallback;\n }\n}\n\nexport async function getHiveEngineOrderBook(\n symbol: string,\n limit: number = 50\n): Promise<{ buy: T[]; sell: T[] }> {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buy, sell] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"price\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"price\", descending: false }],\n },\n },\n []\n ),\n ]);\n\n const sortByPriceDesc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return right - left;\n });\n const sortByPriceAsc = (items: T[]) =>\n items.sort((a, b) => {\n const left = Number((a as EngineOrderBookEntry).price ?? 0);\n const right = Number((b as EngineOrderBookEntry).price ?? 0);\n return left - right;\n });\n\n return {\n buy: sortByPriceDesc(buy),\n sell: sortByPriceAsc(sell),\n };\n}\n\nexport async function getHiveEngineTradeHistory>(\n symbol: string,\n limit: number = 50\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"tradesHistory\",\n query: { symbol },\n limit,\n offset: 0,\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineOpenOrders(\n account: string,\n symbol: string,\n limit: number = 100\n): Promise {\n const baseParams = {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n query: { symbol, account },\n limit,\n offset: 0,\n },\n id: 1,\n };\n\n const [buyRaw, sellRaw] = await Promise.all([\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"buyBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n engineRpcSafe(\n {\n ...baseParams,\n params: {\n ...baseParams.params,\n table: \"sellBook\",\n indexes: [{ index: \"timestamp\", descending: true }],\n },\n },\n []\n ),\n ]);\n\n const formatTotal = (quantity: string, price: string) =>\n (Number(quantity || 0) * Number(price || 0)).toFixed(8);\n\n const buy: HiveEngineOpenOrder[] = buyRaw.map((order) => ({\n id: order.txId,\n type: \"buy\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: order.tokensLocked ?? formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n const sell: HiveEngineOpenOrder[] = sellRaw.map((order) => ({\n id: order.txId,\n type: \"sell\",\n account: order.account,\n symbol: order.symbol,\n quantity: order.quantity,\n price: order.price,\n total: formatTotal(order.quantity, order.price),\n timestamp: Number(order.timestamp ?? 0),\n }));\n\n return [...buy, ...sell].sort((a, b) => b.timestamp - a.timestamp) as T[];\n}\n\n/**\n * Market metrics, optionally narrowed to one symbol or to a list of them.\n *\n * An unfiltered call is served from a single page – the node caps `find` at 1000 rows\n * while Hive engine has far more traded tokens than that – so callers that only care\n * about specific symbols must pass them. Scanning the unfiltered page for a symbol\n * silently reports \"no market\" for everything outside it.\n */\nexport async function getHiveEngineMetrics>(\n symbol?: string | string[],\n account?: string\n): Promise {\n if (Array.isArray(symbol) && symbol.length === 0) {\n return [];\n }\n\n const symbolQuery = Array.isArray(symbol)\n ? { symbol: { $in: symbol } }\n : symbol\n ? { symbol }\n : {};\n\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"market\",\n table: \"metrics\",\n query: {\n ...symbolQuery,\n ...(account ? { account } : {}),\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMarket>(\n account?: string,\n symbol?: string | string[]\n): Promise {\n return getHiveEngineMetrics(symbol, account);\n}\n\nexport async function getHiveEngineTokensBalances>(\n username: string\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"balances\",\n query: {\n account: username,\n },\n },\n id: 1,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokensMetadata>(\n tokens: string[]\n): Promise {\n return engineRpcSafe(\n {\n jsonrpc: \"2.0\",\n method: \"find\",\n params: {\n contract: \"tokens\",\n table: \"tokens\",\n query: {\n symbol: { $in: tokens },\n },\n },\n id: 2,\n },\n []\n );\n}\n\nexport async function getHiveEngineTokenTransactions>(\n username: string,\n symbol: string,\n limit: number,\n offset: number\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-account-history\", baseUrl);\n url.searchParams.set(\"account\", username);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"limit\", limit.toString());\n url.searchParams.set(\"offset\", offset.toString());\n\n const response = await fetchApi(url.toString(), {\n method: \"GET\",\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – account history failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineTokenMetrics>(\n symbol: string,\n interval = \"daily\"\n): Promise {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const url = new URL(\"/private-api/engine-chart-api\", baseUrl);\n url.searchParams.set(\"symbol\", symbol);\n url.searchParams.set(\"interval\", interval);\n\n const response = await fetchApi(url.toString(), {\n headers: { \"Content-type\": \"application/json\" },\n });\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – chart failed with ${response.status}`\n );\n }\n\n return (await response.json()) as T[];\n}\n\nexport async function getHiveEngineUnclaimedRewards>(\n username: string\n): Promise> {\n const fetchApi = getBoundFetch();\n const baseUrl = ConfigManager.getValidatedBaseUrl();\n const response = await fetchApi(\n `${baseUrl}/private-api/engine-reward-api/${username}?hive=1`\n );\n\n if (!response.ok) {\n throw new Error(\n `[SDK][HiveEngine] – rewards failed with ${response.status}`\n );\n }\n\n return (await response.json()) as Record;\n}\n","import { getHiveEngineTokensBalances } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenBalance } from \"../types\";\n\nexport function getHiveEngineTokensBalancesQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"balances\", username] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensBalances(username);\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMarketResponse } from \"../types\";\nimport { getHiveEngineTokensMarket } from \"../requests\";\n\nexport function getHiveEngineTokensMarketQueryOptions() {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"markets\"],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMarket();\n },\n });\n}\n","import { getHiveEngineTokensMetadata } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenMetadataResponse } from \"../types\";\n\nexport function getHiveEngineTokensMetadataQueryOptions(tokens: string[]) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"metadata-list\", tokens] as const,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokensMetadata(tokens);\n },\n });\n}\n","import { getHiveEngineTokenTransactions } from \"../requests\";\nimport { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTransaction } from \"../types\";\n\nexport function getHiveEngineTokenTransactionsQueryOptions(\n username: string | undefined,\n symbol: string,\n limit = 20\n) {\n return infiniteQueryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"transactions\", username],\n enabled: !!symbol && !!username,\n initialPageParam: 0,\n queryFn: async ({ pageParam }) => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n return getHiveEngineTokenTransactions(\n username,\n symbol,\n limit,\n pageParam as number\n );\n },\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n (lastPage?.length ?? 0) === limit ? (lastPageParam as number) + limit : undefined,\n getPreviousPageParam: (_firstPage, _allPages, firstPageParam) =>\n (firstPageParam as number) > 0 ? (firstPageParam as number) - limit : undefined,\n });\n}\n","import { getHiveEngineTokenMetrics } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineMetric } from \"../types\";\n\nexport function getHiveEngineTokensMetricsQueryOptions(\n symbol: string,\n interval = \"daily\"\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n return getHiveEngineTokenMetrics(symbol, interval);\n },\n });\n}\n","import { getHiveEngineUnclaimedRewards } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenStatus } from \"../types\";\n\nexport function getHiveEngineUnclaimedRewardsQueryOptions(\n username: string | undefined\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"unclaimed\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n enabled: !!username,\n queryFn: async () => {\n try {\n const data = await getHiveEngineUnclaimedRewards(\n username as string\n );\n return Object.values(data).filter(\n ({ pending_token }) => pending_token > 0\n );\n } catch (e) {\n return [];\n }\n },\n });\n}\n","import { getHiveEngineTokensMarket } from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { HiveEngineTokenInfo } from \"../types\";\n\nexport function getAllHiveEngineTokensQueryOptions(\n account?: string,\n symbol?: string | string[]\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", \"all-tokens\", account, symbol] as const,\n queryFn: async () => {\n return getHiveEngineTokensMarket(account, symbol);\n },\n });\n}\n","interface Options {\n fractionDigits?: number;\n prefix?: string;\n suffix?: string;\n}\n\nexport function formattedNumber(\n value: number | string,\n options: Options | undefined = undefined\n) {\n let opts: Options = {\n fractionDigits: 3,\n prefix: \"\",\n suffix: \"\",\n };\n\n if (options) {\n opts = { ...opts, ...options };\n }\n\n const { fractionDigits, prefix, suffix } = opts;\n\n let out = \"\";\n\n if (prefix) out += prefix + \" \";\n // turn too small values to zero. Bug: https://github.com/adamwdraper/Numeral-js/issues/563\n const av = Math.abs(parseFloat(value.toString())) < 0.0001 ? 0 : value;\n const num = typeof av === \"string\" ? parseFloat(av) : av;\n out += num.toLocaleString(\"en-US\", {\n minimumFractionDigits: fractionDigits,\n maximumFractionDigits: fractionDigits,\n useGrouping: true,\n });\n if (suffix) out += \" \" + suffix;\n\n return out;\n}\n","import { formattedNumber } from \"./formatted-number\";\n\ninterface HiveEngineTokenProps {\n symbol: string;\n name: string;\n icon: string;\n precision: number;\n stakingEnabled: boolean;\n delegationEnabled: boolean;\n balance: string;\n stake: string;\n delegationsIn: string;\n delegationsOut: string;\n usdValue: number;\n}\n\nexport class HiveEngineToken {\n symbol: string;\n name?: string;\n icon?: string;\n\n precision?: number;\n stakingEnabled?: boolean;\n delegationEnabled?: boolean;\n balance: number;\n stake: number;\n stakedBalance: number;\n delegationsIn: number;\n delegationsOut: number;\n usdValue: number;\n\n constructor(props: HiveEngineTokenProps) {\n this.symbol = props.symbol;\n this.name = props.name || \"\";\n this.icon = props.icon || \"\";\n\n this.precision = props.precision || 0;\n this.stakingEnabled = props.stakingEnabled || false;\n this.delegationEnabled = props.delegationEnabled || false;\n this.balance = parseFloat(props.balance) || 0;\n this.stake = parseFloat(props.stake) || 0;\n this.delegationsIn = parseFloat(props.delegationsIn) || 0;\n this.delegationsOut = parseFloat(props.delegationsOut) || 0;\n this.stakedBalance =\n this.stake + this.delegationsIn - this.delegationsOut;\n this.usdValue = props.usdValue;\n }\n\n hasDelegations = (): boolean => {\n if (!this.delegationEnabled) {\n return false;\n }\n\n return this.delegationsIn > 0 && this.delegationsOut > 0;\n };\n\n delegations = (): string => {\n if (!this.hasDelegations()) {\n return \"\";\n }\n\n return `(${formattedNumber(this.stake, {\n fractionDigits: this.precision,\n })} + ${formattedNumber(this.delegationsIn, {\n fractionDigits: this.precision,\n })} - ${formattedNumber(this.delegationsOut, {\n fractionDigits: this.precision,\n })})`;\n };\n\n staked = (): string => {\n if (!this.stakingEnabled) {\n return \"-\";\n }\n\n if (this.stakedBalance < 0.0001) {\n return this.stakedBalance.toString();\n }\n\n return formattedNumber(this.stakedBalance, {\n fractionDigits: this.precision,\n });\n };\n\n balanced = (): string => {\n if (this.balance < 0.0001) {\n return this.balance.toString();\n }\n\n return formattedNumber(this.balance, { fractionDigits: this.precision });\n };\n}\n","import {\n getHiveEngineTokensBalances,\n getHiveEngineTokensMarket,\n getHiveEngineTokensMetadata,\n} from \"../requests\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type {\n HiveEngineTokenBalance,\n Token,\n TokenMetadata,\n HiveEngineTokenInfo,\n} from \"../types\";\nimport { HiveEngineToken } from \"../utils\";\n\ninterface DynamicProps {\n base: number;\n quote: number;\n}\n\nexport function getHiveEngineBalancesWithUsdQueryOptions(\n account: string,\n dynamicProps?: DynamicProps,\n allTokens?: HiveEngineTokenInfo[]\n) {\n return queryOptions({\n queryKey: [\n \"assets\",\n \"hive-engine\",\n \"balances-with-usd\",\n account,\n dynamicProps,\n allTokens,\n ] as const,\n queryFn: async () => {\n if (!account) {\n throw new Error(\"[HiveEngine] No account in a balances query\");\n }\n\n const balances = await getHiveEngineTokensBalances(account);\n\n const tokens = await getHiveEngineTokensMetadata(\n balances.map((t) => t.symbol)\n );\n\n const pricePerHive = dynamicProps\n ? dynamicProps.base / dynamicProps.quote\n : 0;\n const providedMetrics: ReadonlyArray = Array.isArray(\n allTokens\n )\n ? allTokens\n : [];\n\n // Whatever the caller passed comes from an unfiltered metrics call, which the node\n // caps at 1000 rows – held tokens outside that page have no price and used to be\n // valued at zero, understating the wallet. Ask for the missing ones by symbol.\n const unpricedSymbols = balances\n .map((balance) => balance.symbol)\n .filter(\n (symbol) =>\n symbol !== \"SWAP.HIVE\" &&\n !providedMetrics.some((metric) => metric.symbol === symbol)\n );\n\n const metrics: ReadonlyArray = [\n ...providedMetrics,\n ...(unpricedSymbols.length\n ? await getHiveEngineTokensMarket(\n undefined,\n unpricedSymbols\n )\n : []),\n ];\n\n return balances.map((balance) => {\n const token = tokens.find((t) => t.symbol === balance.symbol);\n let tokenMetadata: TokenMetadata | undefined;\n\n if (token?.metadata) {\n try {\n tokenMetadata = JSON.parse(token.metadata) as TokenMetadata;\n } catch {\n tokenMetadata = undefined;\n }\n }\n\n const metric = metrics.find((m) => m.symbol === balance.symbol);\n const lastPrice = Number(metric?.lastPrice ?? \"0\");\n const balanceAmount = Number(balance.balance);\n\n const usdValue =\n balance.symbol === \"SWAP.HIVE\"\n ? pricePerHive * balanceAmount\n : lastPrice === 0\n ? 0\n : Number(\n (lastPrice * pricePerHive * balanceAmount).toFixed(10)\n );\n\n return new HiveEngineToken({\n symbol: balance.symbol,\n name: token?.name ?? balance.symbol,\n icon: tokenMetadata?.icon ?? \"\",\n precision: token?.precision ?? 0,\n stakingEnabled: token?.stakingEnabled ?? false,\n delegationEnabled: token?.delegationEnabled ?? false,\n balance: balance.balance,\n stake: balance.stake,\n delegationsIn: balance.delegationsIn,\n delegationsOut: balance.delegationsOut,\n usdValue,\n });\n });\n },\n enabled: !!account,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getHiveEngineTokensMetadataQueryOptions } from \"./get-hive-engine-tokens-metadata-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"./get-hive-engine-tokens-balances-query-options\";\nimport { getAllHiveEngineTokensQueryOptions } from \"./get-all-hive-engine-tokens-query-options\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"@/modules/wallet/queries/get-hive-asset-general-info-query-options\";\n\nexport function getHiveEngineTokenGeneralInfoQueryOptions(\n username?: string,\n symbol?: string\n) {\n return queryOptions({\n queryKey: [\"assets\", \"hive-engine\", symbol, \"general-info\", username],\n enabled: !!symbol && !!username,\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n if (!symbol || !username) {\n throw new Error(\n \"[SDK][HiveEngine] – token or username missed\"\n );\n }\n const queryClient = getQueryClient();\n const hiveQuery = getHiveAssetGeneralInfoQueryOptions(username);\n await queryClient.prefetchQuery(hiveQuery);\n const hiveData = queryClient.getQueryData(\n hiveQuery.queryKey\n );\n\n const metadataList = await queryClient.ensureQueryData(\n getHiveEngineTokensMetadataQueryOptions([symbol])\n );\n\n const balanceList = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n // Scoped to this symbol: the unfiltered metrics call is capped at 1000 rows, so a\n // token outside that page reported no market and rendered a zero price.\n const marketList = await queryClient.ensureQueryData(\n getAllHiveEngineTokensQueryOptions(undefined, symbol)\n );\n\n const metadata = metadataList?.find((i) => i.symbol === symbol);\n const balance = balanceList?.find((i) => i.symbol === symbol);\n const market = marketList?.find((i) => i.symbol === symbol);\n\n const lastPrice = +(market?.lastPrice ?? \"0\");\n\n const liquidBalance = parseFloat(balance?.balance ?? \"0\");\n const stakedBalance = parseFloat(balance?.stake ?? \"0\");\n const unstakingBalance = parseFloat(balance?.pendingUnstake ?? \"0\");\n\n const parts: GeneralAssetInfo[\"parts\"] = [\n { name: \"liquid\", balance: liquidBalance },\n { name: \"staked\", balance: stakedBalance },\n ];\n\n if (unstakingBalance > 0) {\n parts.push({ name: \"unstaking\", balance: unstakingBalance });\n }\n\n return {\n name: symbol,\n title: metadata?.name ?? \"\",\n price: lastPrice === 0 ? 0 : Number(lastPrice * (hiveData?.price ?? 0)),\n accountBalance: liquidBalance + stakedBalance,\n layer: \"ENGINE\",\n parts,\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\nimport { PointTransaction } from \"../types/point-transaction\";\n\ninterface PointsResponse {\n points: string;\n unclaimed_points: string;\n}\n\nexport function getPointsQueryOptions(username?: string, filter = 0) {\n return queryOptions({\n queryKey: [\"points\", username, filter],\n queryFn: async () => {\n if (!username) {\n throw new Error(\"Get points query – username wasn't provided\");\n }\n\n const name = username.replace(\"@\", \"\");\n\n // Get points\n const pointsResponse = await fetch(CONFIG.privateApiHost + \"/private-api/points\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name }),\n });\n\n if (!pointsResponse.ok) {\n throw new Error(`Failed to fetch points: ${pointsResponse.status}`);\n }\n\n const points = (await pointsResponse.json()) as PointsResponse;\n\n // Get transactions\n const transactionsResponse = await fetch(\n CONFIG.privateApiHost + \"/private-api/point-list\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ username: name, type: filter }),\n }\n );\n\n if (!transactionsResponse.ok) {\n throw new Error(`Failed to fetch point transactions: ${transactionsResponse.status}`);\n }\n\n const transactions = (await transactionsResponse.json()) as PointTransaction[];\n\n return {\n points: points.points,\n uPoints: points.unclaimed_points,\n transactions,\n } as const;\n },\n staleTime: 30000,\n refetchOnMount: true,\n enabled: !!username,\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"@/modules/wallet/types\";\nimport { getPointsQueryOptions } from \"./get-points-query-options\";\n\nexport function getPointsAssetGeneralInfoQueryOptions(username: string) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"general-info\", username],\n staleTime: 60000,\n refetchInterval: 90000,\n queryFn: async () => {\n await getQueryClient().prefetchQuery(getPointsQueryOptions(username));\n const data = getQueryClient().getQueryData(\n getPointsQueryOptions(username).queryKey\n );\n return {\n name: \"POINTS\",\n title: \"Ecency Points\",\n price: 0.002,\n accountBalance: +(data?.points ?? 0),\n } satisfies GeneralAssetInfo;\n },\n });\n}\n","import { CONFIG } from \"@/modules/core/config\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { PointTransaction } from \"../types\";\nimport { PointTransactionType } from \"../types\";\nimport type { GeneralAssetTransaction } from \"@/modules/wallet/types\";\n\nexport function getPointsAssetTransactionsQueryOptions(\n username: string | undefined,\n type?: PointTransactionType\n) {\n return queryOptions({\n queryKey: [\"assets\", \"points\", \"transactions\", username, type],\n queryFn: async () => {\n const response = await fetch(\n `${CONFIG.privateApiHost}/private-api/point-list`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n username,\n type: type ?? 0,\n }),\n }\n );\n const data = (await response.json()) as PointTransaction[];\n return data.map(({ created, type, amount, id, sender, receiver, memo }) => ({\n created: new Date(created),\n type,\n results: [\n {\n amount: parseFloat(amount),\n asset: \"POINTS\",\n },\n ],\n id,\n from: sender ?? undefined,\n to: receiver ?? undefined,\n memo: memo ?? undefined,\n })) satisfies GeneralAssetTransaction[];\n },\n });\n}\n","import { getQueryClient } from \"@/modules/core\";\nimport { getCurrencyRate } from \"@/modules/market\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport type { GeneralAssetInfo } from \"../types\";\nimport { getHiveAssetGeneralInfoQueryOptions } from \"./get-hive-asset-general-info-query-options\";\nimport { getHbdAssetGeneralInfoQueryOptions } from \"./get-hbd-asset-general-info-query-options\";\nimport { getHivePowerAssetGeneralInfoQueryOptions } from \"./get-hive-power-asset-general-info-query-options\";\nimport { getHiveEngineTokensBalancesQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getHiveEngineTokenGeneralInfoQueryOptions } from \"@/modules/hive-engine/queries\";\nimport { getPointsAssetGeneralInfoQueryOptions } from \"@/modules/points/queries\";\nimport {\n getPortfolioQueryOptions,\n type PortfolioResponse,\n type PortfolioWalletItem,\n} from \"./get-portfolio-query-options\";\n\ninterface Options {\n refetch?: boolean;\n currency?: string;\n}\n\nexport function getAccountWalletAssetInfoQueryOptions(\n username: string,\n asset: string,\n options: Options = { refetch: false }\n) {\n const queryClient = getQueryClient();\n const currency = options.currency ?? \"usd\";\n\n const fetchQuery = async (qo: any) => {\n if (options.refetch) {\n await queryClient.fetchQuery(qo);\n } else {\n await queryClient.prefetchQuery(qo);\n }\n return queryClient.getQueryData(qo.queryKey);\n };\n\n const convertPriceToUserCurrency = async (\n assetInfo: GeneralAssetInfo | undefined\n ): Promise => {\n if (!assetInfo || currency === \"usd\") {\n return assetInfo;\n }\n\n try {\n const conversionRate = await getCurrencyRate(currency);\n return {\n ...assetInfo,\n price: assetInfo.price * conversionRate,\n };\n } catch (error) {\n console.warn(`Failed to convert price from USD to ${currency}:`, error);\n return assetInfo;\n }\n };\n\n const portfolioQuery = getPortfolioQueryOptions(username, currency, true);\n\n const getPortfolioAssetInfo = async () => {\n try {\n const portfolio: PortfolioResponse = await queryClient.fetchQuery(portfolioQuery);\n const assetItem = portfolio.wallets.find(\n (item: PortfolioWalletItem) =>\n item.symbol.toUpperCase() === asset.toUpperCase()\n );\n\n if (!assetItem) return undefined;\n\n const parts: Array<{ name: string; balance: number }> = [];\n\n if (assetItem.liquid !== undefined && assetItem.liquid !== null) {\n parts.push({ name: \"liquid\", balance: assetItem.liquid });\n }\n\n if (assetItem.staked !== undefined && assetItem.staked !== null && assetItem.staked > 0) {\n parts.push({ name: \"staked\", balance: assetItem.staked });\n }\n\n if (assetItem.savings !== undefined && assetItem.savings !== null && assetItem.savings > 0) {\n parts.push({ name: \"savings\", balance: assetItem.savings });\n }\n\n if (assetItem.extraData && Array.isArray(assetItem.extraData)) {\n for (const extraItem of assetItem.extraData) {\n if (!extraItem || typeof extraItem !== \"object\") continue;\n\n const dataKey = extraItem.dataKey;\n const value = extraItem.value;\n\n if (typeof value === \"string\") {\n const cleanValue = value.replace(/,/g, \"\");\n const match = cleanValue.match(/[+-]?\\s*(\\d+(?:\\.\\d+)?)/);\n if (match) {\n const numValue = Math.abs(Number.parseFloat(match[1]));\n\n if (dataKey === \"delegated_hive_power\") {\n parts.push({ name: \"outgoing_delegations\", balance: numValue });\n } else if (dataKey === \"received_hive_power\") {\n parts.push({ name: \"incoming_delegations\", balance: numValue });\n } else if (dataKey === \"powering_down_hive_power\") {\n parts.push({ name: \"pending_power_down\", balance: numValue });\n }\n }\n }\n }\n }\n\n return {\n name: assetItem.symbol,\n title: assetItem.name,\n price: assetItem.fiatRate,\n accountBalance: assetItem.balance,\n apr: assetItem.apr?.toString(),\n layer: assetItem.layer,\n pendingRewards: assetItem.pendingRewards,\n parts,\n } as GeneralAssetInfo;\n } catch {\n return undefined;\n }\n };\n\n return queryOptions({\n queryKey: [\"ecency-wallets\", \"asset-info\", username, asset, currency],\n queryFn: async () => {\n const portfolioAssetInfo = await getPortfolioAssetInfo();\n\n if (portfolioAssetInfo && portfolioAssetInfo.price > 0) {\n return portfolioAssetInfo;\n }\n\n let assetInfo: GeneralAssetInfo | undefined;\n\n if (asset === \"HIVE\") {\n assetInfo = await fetchQuery(getHiveAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HP\") {\n assetInfo = await fetchQuery(getHivePowerAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"HBD\") {\n assetInfo = await fetchQuery(getHbdAssetGeneralInfoQueryOptions(username));\n } else if (asset === \"POINTS\") {\n assetInfo = await fetchQuery(getPointsAssetGeneralInfoQueryOptions(username));\n } else {\n // Check if it's a Hive Engine token\n const balances = await queryClient.ensureQueryData(\n getHiveEngineTokensBalancesQueryOptions(username)\n );\n\n if (balances.some((balance) => balance.symbol === asset)) {\n assetInfo = await fetchQuery(\n getHiveEngineTokenGeneralInfoQueryOptions(username, asset)\n );\n } else if (portfolioAssetInfo) {\n // Unknown asset but portfolio has data — use it as-is\n return portfolioAssetInfo;\n } else {\n throw new Error(\n `[SDK][Wallet] – unrecognized asset \"${asset}\"`\n );\n }\n }\n\n // If portfolio had rich data (parts, balance) but zero price,\n // merge the fallback price into the portfolio data\n if (portfolioAssetInfo && assetInfo && assetInfo.price > 0) {\n const converted = await convertPriceToUserCurrency(assetInfo);\n return {\n ...portfolioAssetInfo,\n price: converted!.price,\n };\n }\n\n return await convertPriceToUserCurrency(assetInfo);\n },\n });\n}\n","export enum AssetOperation {\n // Common\n Transfer = \"transfer\",\n\n // APR\n TransferToSavings = \"transfer-saving\",\n WithdrawFromSavings = \"withdraw-saving\",\n Delegate = \"delegate\",\n PowerUp = \"power-up\",\n PowerDown = \"power-down\",\n WithdrawRoutes = \"withdraw-routes\",\n ClaimInterest = \"claim-interest\",\n Swap = \"swap\",\n Convert = \"convert\",\n\n // Points\n Gift = \"gift\",\n Promote = \"promote\",\n Claim = \"claim\",\n Buy = \"buy\",\n\n // Layer 2\n Stake = \"stake\",\n Unstake = \"unstake\",\n Undelegate = \"undelegate\",\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for transferring tokens.\n */\nexport interface TransferPayload {\n /** Recipient account */\n to: string;\n /** Amount with asset symbol (e.g., \"1.000 HIVE\", \"5.000 HBD\") */\n amount: string;\n /** Transfer memo */\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring tokens.\n *\n * This mutation broadcasts a transfer operation to send HIVE or HBD\n * to another account. **Requires ACTIVE authority**.\n *\n * Uses `useBroadcastMutation` with the smart auth strategy:\n * - Adapter determines login type and dispatches to appropriate method\n * - If active key not available (common on web), triggers `showAuthUpgradeUI`\n * - Supports keychain, hivesigner, hiveauth, and direct key signing\n *\n * @param username - The username sending the transfer (required for broadcast)\n * @param auth - Authentication context with platform adapter\n *\n * @returns React Query mutation result\n */\nexport function useTransfer(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer\"],\n username,\n (payload) => [\n buildTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildPointTransferOp } from \"@/modules/operations/builders\";\n\nexport interface TransferPointPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\n/**\n * React Query mutation hook for transferring Ecency points.\n *\n * Uses `ecency_point_transfer` custom_json operation with ACTIVE authority.\n */\nexport function useTransferPoint(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-point\"],\n username,\n (payload) => [\n buildPointTransferOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildDelegateVestingSharesOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for delegating Hive Power (vesting shares).\n */\nexport interface DelegateVestingSharesPayload {\n /** Account receiving HP delegation */\n delegatee: string;\n /** Amount of VESTS to delegate (e.g., \"1000.000000 VESTS\"). Use \"0.000000 VESTS\" to remove delegation. */\n vestingShares: string;\n}\n\n/**\n * React Query mutation hook for delegating Hive Power (HP).\n *\n * This mutation broadcasts a delegate_vesting_shares operation to delegate HP\n * to another account. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username delegating HP (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Delegation operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Delegation Mechanics:**\n * - Delegated HP can be used by the delegatee for resource credits\n * - Delegatee CANNOT power down or transfer the delegated HP\n * - Delegation can be removed by setting vestingShares to \"0.000000 VESTS\"\n * - Removing delegation has a 5-day cooldown before HP returns to delegator\n *\n * **Post-Broadcast Actions:**\n * - Invalidates delegations list cache to show updated delegation\n * - Invalidates account data for both delegator and delegatee\n *\n * @example\n * ```typescript\n * const delegateMutation = useDelegateVestingShares(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Delegate HP\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '1000.000000 VESTS'\n * });\n *\n * // Remove delegation\n * delegateMutation.mutate({\n * delegatee: 'alice',\n * vestingShares: '0.000000 VESTS'\n * });\n * ```\n */\nexport function useDelegateVestingShares(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-vesting-shares\"],\n username,\n (payload) => [\n buildDelegateVestingSharesOp(\n username!,\n payload.delegatee,\n payload.vestingShares\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.delegatee),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildSetWithdrawVestingRouteOp } from \"@/modules/operations/builders\";\n\n/**\n * Payload for setting withdraw vesting route.\n */\nexport interface SetWithdrawVestingRoutePayload {\n /** Account receiving withdrawn vesting */\n toAccount: string;\n /** Percentage to route (0-10000, where 10000 = 100%). Already scaled. */\n percent: number;\n /** Auto convert to vesting (power up) */\n autoVest: boolean;\n}\n\n/**\n * React Query mutation hook for setting withdraw vesting route.\n *\n * This mutation broadcasts a set_withdraw_vesting_route operation to configure\n * where withdrawn VESTS (power down) are sent. **Requires ACTIVE authority**, not posting.\n *\n * @param username - The username setting withdraw route (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **IMPORTANT: Active Authority Required**\n * - Withdraw route operations require ACTIVE key, not posting key\n * - Make sure your auth adapter provides getActiveKey() method\n * - Keychain/HiveAuth will prompt for Active authority\n *\n * **Withdraw Route Mechanics:**\n * - Routes a percentage of power down (withdraw_vesting) to another account\n * - Percent must be between 0-10000 (where 10000 = 100%)\n * - Multiple routes can be set, total cannot exceed 100%\n * - autoVest=true converts withdrawn VESTS to HP in destination account\n * - autoVest=false converts withdrawn VESTS to liquid HIVE\n *\n * **Post-Broadcast Actions:**\n * - Invalidates withdraw routes cache to show updated routes\n * - Invalidates account data for both accounts\n *\n * @example\n * ```typescript\n * const setRouteMutation = useSetWithdrawVestingRoute(username, {\n * adapter: {\n * ...myAdapter,\n * getActiveKey: async (username) => getActiveKeyFromStorage(username)\n * },\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Route 50% of power down to another account (auto vest)\n * setRouteMutation.mutate({\n * toAccount: 'alice',\n * percent: 5000, // 50% (already scaled)\n * autoVest: true\n * });\n *\n * // Route 100% of power down to another account (liquid HIVE)\n * setRouteMutation.mutate({\n * toAccount: 'bob',\n * percent: 10000, // 100% (already scaled)\n * autoVest: false\n * });\n * ```\n */\nexport function useSetWithdrawVestingRoute(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"set-withdraw-vesting-route\"],\n username,\n (payload) => [\n buildSetWithdrawVestingRouteOp(\n username!,\n payload.toAccount,\n payload.percent,\n payload.autoVest\n )\n ],\n async (_result, variables) => {\n // Cache invalidation\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.wallet.withdrawRoutes(username!),\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.toAccount)\n ]);\n },\n auth,\n 'active', // IMPORTANT: Active authority required\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface TransferEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n memo: string;\n}\n\nexport function useTransferEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"transfer\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n memo: payload.memo\n }\n });\n return [[\"custom_json\", {\n required_auths: [username!],\n required_posting_auths: [],\n id: \"ssc-mainnet-hive\",\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n}\n\nexport function useTransferToSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-savings\"],\n username,\n (payload) => [\n buildTransferToSavingsOp(username!, payload.to, payload.amount, payload.memo)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferFromSavingsOp } from \"@/modules/operations/builders\";\n\nexport interface TransferFromSavingsPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useTransferFromSavings(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-from-savings\"],\n username,\n (payload) => [\n buildTransferFromSavingsOp(username!, payload.to, payload.amount, payload.memo, payload.requestId)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildTransferToVestingOp } from \"@/modules/operations/builders\";\n\nexport interface TransferToVestingPayload {\n to: string;\n amount: string;\n}\n\nexport function useTransferToVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"transfer-to-vesting\"],\n username,\n (payload) => [\n buildTransferToVestingOp(username!, payload.to, payload.amount)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildWithdrawVestingOp } from \"@/modules/operations/builders\";\n\nexport interface WithdrawVestingPayload {\n vestingShares: string;\n}\n\nexport function useWithdrawVesting(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"withdraw-vesting\"],\n username,\n (payload) => [\n buildWithdrawVestingOp(username!, payload.vestingShares)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildConvertOp, buildCollateralizedConvertOp } from \"@/modules/operations/builders\";\n\nexport interface ConvertPayload {\n amount: string;\n requestId: number;\n collateralized?: boolean;\n}\n\nexport function useConvert(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"convert\"],\n username,\n (payload) => [\n payload.collateralized\n ? buildCollateralizedConvertOp(username!, payload.amount, payload.requestId)\n : buildConvertOp(username!, payload.amount, payload.requestId)\n ],\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimInterestOps } from \"@/modules/operations/builders\";\n\nexport interface ClaimInterestPayload {\n to: string;\n amount: string;\n memo: string;\n requestId: number;\n}\n\nexport function useClaimInterest(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-interest\"],\n username,\n (payload) => buildClaimInterestOps(username!, payload.to, payload.amount, payload.memo, payload.requestId),\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys, getQueryClient } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { buildClaimRewardBalanceOp } from \"@/modules/operations/builders\";\n\nexport interface ClaimRewardsPayload {\n rewardHive: string;\n rewardHbd: string;\n rewardVests: string;\n}\n\nconst CLAIM_REWARDS_INVALIDATION_DELAY_MS = 5000;\nconst pendingInvalidationTimers = new Map>();\n\nexport function useClaimRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-rewards\"],\n username,\n (payload) => [\n buildClaimRewardBalanceOp(username!, payload.rewardHive, payload.rewardHbd, payload.rewardVests)\n ],\n () => {\n const timerKey = username ?? \"__anonymous__\";\n const keysToInvalidate = [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username],\n QueryKeys.assets.hiveGeneralInfo(username!),\n QueryKeys.assets.hbdGeneralInfo(username!),\n QueryKeys.assets.hivePowerGeneralInfo(username!),\n ];\n\n // Delay invalidation to allow blockchain to propagate the transaction.\n // Immediate invalidation would fetch stale (pre-confirmation) data.\n const existingTimer = pendingInvalidationTimers.get(timerKey);\n if (existingTimer) {\n clearTimeout(existingTimer);\n pendingInvalidationTimers.delete(timerKey);\n }\n\n const timer = setTimeout(async () => {\n try {\n const qc = getQueryClient();\n const results = await Promise.allSettled(\n keysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))\n );\n const rejected = results.filter((result) => result.status === \"rejected\");\n if (rejected.length > 0) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation rejected\", {\n username,\n rejectedCount: rejected.length,\n rejected\n });\n }\n } catch (error) {\n console.error(\"[SDK][Wallet][useClaimRewards] delayed invalidation failed\", {\n username,\n error\n });\n } finally {\n pendingInvalidationTimers.delete(timerKey);\n }\n }, CLAIM_REWARDS_INVALIDATION_DELAY_MS);\n\n pendingInvalidationTimers.set(timerKey, timer);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface DelegateEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useDelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"delegate\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UndelegateEngineTokenPayload {\n from: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUndelegateEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"undelegate-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"undelegate\",\n contractPayload: {\n symbol: payload.symbol,\n from: payload.from,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface StakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useStakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"stake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"stake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface UnstakeEngineTokenPayload {\n to: string;\n symbol: string;\n quantity: string;\n}\n\nexport function useUnstakeEngineToken(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"unstake-engine-token\"],\n username,\n (payload) => {\n const json = JSON.stringify({\n contractName: \"tokens\",\n contractAction: \"unstake\",\n contractPayload: {\n symbol: payload.symbol,\n to: payload.to,\n quantity: payload.quantity,\n }\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface ClaimEngineRewardsPayload {\n tokens: string[];\n}\n\nexport function useClaimEngineRewards(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"claim-engine-rewards\"],\n username,\n (payload) => {\n const json = JSON.stringify(payload.tokens.map((symbol) => ({ symbol })));\n return [[\"custom_json\", {\n id: \"scot_claim_token\",\n required_auths: [],\n required_posting_auths: [username!],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'posting',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport { QueryKeys } from \"@/modules/core\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface EngineMarketOrderPayload {\n action: \"buy\" | \"sell\" | \"cancel\";\n symbol: string;\n quantity?: string;\n price?: string;\n orderId?: string;\n orderType?: \"buy\" | \"sell\";\n}\n\nexport function useEngineMarketOrder(username: string | undefined, auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"engine-market-order\"],\n username,\n (payload) => {\n let contractPayload: Record;\n let contractAction: string;\n\n if (payload.action === \"cancel\") {\n contractAction = \"cancel\";\n contractPayload = {\n type: payload.orderType!,\n id: payload.orderId!,\n };\n } else {\n contractAction = payload.action;\n contractPayload = {\n symbol: payload.symbol,\n quantity: payload.quantity!,\n price: payload.price!,\n };\n }\n\n const json = JSON.stringify({\n contractName: \"market\",\n contractAction,\n contractPayload,\n });\n return [[\"custom_json\", {\n id: \"ssc-mainnet-hive\",\n required_auths: [username!],\n required_posting_auths: [],\n json,\n }] as Operation];\n },\n async () => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n [\"ecency-wallets\", \"asset-info\", username],\n [\"wallet\", \"portfolio\", \"v2\", username]\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation } from \"@/modules/core/mutations\";\nimport type { BroadcastMode } from \"@/modules/core/mutations\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { getQueryClient } from \"@/modules/core\";\nimport type { AuthorityLevel } from \"@/modules/operations/authority-map\";\nimport { AssetOperation } from \"../types\";\nimport {\n buildTransferOp,\n buildTransferToSavingsOp,\n buildTransferFromSavingsOp,\n buildTransferToVestingOp,\n buildWithdrawVestingOp,\n buildDelegateVestingSharesOp,\n buildSetWithdrawVestingRouteOp,\n buildConvertOp,\n buildClaimInterestOps,\n buildPointTransferOp,\n buildEngineOp,\n buildEngineClaimOp,\n} from \"@/modules/operations/builders\";\nimport type { Operation } from \"../../../hive-tx\";\n\nexport interface WalletOperationPayload {\n from: string;\n to?: string;\n amount?: string;\n memo?: string;\n request_id?: number;\n from_account?: string;\n to_account?: string;\n percent?: number;\n auto_vest?: boolean;\n mode?: string;\n [key: string]: unknown;\n}\n\nfunction buildHiveOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\", memo = \"\" } = payload;\n const requestId = payload.request_id ?? (Date.now() >>> 0);\n\n switch (asset) {\n case \"HIVE\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.PowerUp:\n return [buildTransferToVestingOp(from, to, amount)];\n }\n break;\n\n case \"HBD\":\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildTransferOp(from, to, amount, memo)];\n case AssetOperation.TransferToSavings:\n return [buildTransferToSavingsOp(from, to, amount, memo)];\n case AssetOperation.WithdrawFromSavings:\n return [buildTransferFromSavingsOp(from, to, amount, memo, requestId)];\n case AssetOperation.ClaimInterest:\n return buildClaimInterestOps(from, to, amount, memo, requestId);\n case AssetOperation.Convert:\n return [buildConvertOp(from, amount, Math.floor(Date.now() / 1000))];\n }\n break;\n\n case \"HP\":\n switch (operation) {\n case AssetOperation.PowerDown:\n return [buildWithdrawVestingOp(from, amount)];\n case AssetOperation.Delegate:\n return [buildDelegateVestingSharesOp(from, to, amount)];\n case AssetOperation.WithdrawRoutes:\n return [buildSetWithdrawVestingRouteOp(\n payload.from_account ?? from,\n payload.to_account ?? to,\n payload.percent ?? 0,\n payload.auto_vest ?? false\n )];\n }\n break;\n\n case \"POINTS\":\n if (operation === AssetOperation.Transfer || operation === AssetOperation.Gift) {\n return [buildPointTransferOp(from, to, amount, memo)];\n }\n break;\n }\n\n return null;\n}\n\nfunction buildEngineOperations(\n asset: string,\n operation: AssetOperation,\n payload: WalletOperationPayload\n): Operation[] | null {\n const { from, to = \"\", amount = \"\" } = payload;\n const quantity = typeof amount === \"string\" && amount.includes(\" \")\n ? amount.split(\" \")[0]\n : String(amount);\n\n switch (operation) {\n case AssetOperation.Transfer:\n return [buildEngineOp(from, \"transfer\", {\n symbol: asset, to, quantity, memo: payload.memo ?? \"\"\n })];\n case AssetOperation.Stake:\n return [buildEngineOp(from, \"stake\", { symbol: asset, to, quantity })];\n case AssetOperation.Unstake:\n return [buildEngineOp(from, \"unstake\", { symbol: asset, to, quantity })];\n case AssetOperation.Delegate:\n return [buildEngineOp(from, \"delegate\", { symbol: asset, to, quantity })];\n case AssetOperation.Undelegate:\n return [buildEngineOp(from, \"undelegate\", { symbol: asset, from: to, quantity })];\n case AssetOperation.Claim:\n return [buildEngineClaimOp(from, [asset])];\n }\n\n return null;\n}\n\n/**\n * Determines authority level for a wallet operation.\n * Engine token claims use posting authority; everything else uses active.\n */\nfunction getWalletOperationAuthority(operation: AssetOperation): AuthorityLevel {\n if (operation === AssetOperation.Claim) {\n return 'posting';\n }\n return 'active';\n}\n\n/**\n * Meta-mutation hook that dispatches wallet operations based on asset and operation type.\n *\n * Supports HIVE, HBD, HP, POINTS, and Hive Engine tokens.\n * Uses `useBroadcastMutation` for unified auth handling via `AuthContextV2`.\n *\n * @param username - The Hive account performing the operation\n * @param asset - The asset symbol (e.g., \"HIVE\", \"HBD\", \"HP\", \"POINTS\", or engine token)\n * @param operation - The operation type from AssetOperation enum\n * @param auth - Auth context for broadcasting\n */\nexport function useWalletOperation(\n username: string | undefined,\n asset: string,\n operation: AssetOperation,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n operation as any\n );\n\n return useBroadcastMutation(\n [\"ecency-wallets\", asset, operation],\n username,\n (payload) => {\n // Try native Hive + POINTS operations\n const hiveOps = buildHiveOperations(asset, operation, payload);\n if (hiveOps) return hiveOps;\n\n // Try engine token operations\n const engineOps = buildEngineOperations(asset, operation, payload);\n if (engineOps) return engineOps;\n\n throw new Error(`[SDK][Wallet] – no operation builder for asset=\"${asset}\" operation=\"${operation}\"`);\n },\n () => {\n recordActivity();\n\n const keysToInvalidate: (string | undefined)[][] = [];\n\n // Invalidate asset-specific queries (prefix-matches all currency variants)\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, asset]);\n\n if (asset === \"HIVE\") {\n keysToInvalidate.push([\"ecency-wallets\", \"asset-info\", username, \"HP\"]);\n }\n\n // Invalidate portfolio (prefix-matches all currency/filter variants)\n keysToInvalidate.push([\"wallet\", \"portfolio\", \"v2\", username]);\n\n // Delay invalidation to allow blockchain to process\n setTimeout(() => {\n keysToInvalidate.forEach((key) => {\n getQueryClient().invalidateQueries({ queryKey: key });\n });\n }, 5000);\n },\n auth,\n getWalletOperationAuthority(operation),\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, invalidateAfterBroadcast, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildDelegateRcOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface DelegateRcPayload {\n to: string;\n maxRc: string | number;\n}\n\nexport function useDelegateRc(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"wallet\", \"delegate-rc\"],\n username,\n ({ to, maxRc }) => [\n buildDelegateRcOp(username!, to, maxRc)\n ],\n async (_result, variables) => {\n await invalidateAfterBroadcast(auth?.adapter, broadcastMode, [\n QueryKeys.accounts.full(username),\n QueryKeys.accounts.full(variables.to),\n QueryKeys.resourceCredits.account(username!),\n QueryKeys.resourceCredits.account(variables.to),\n ]);\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessVoteOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\n/**\n * Payload for voting for a witness.\n */\nexport interface WitnessVotePayload {\n /** Witness account name to vote for/against */\n witness: string;\n /** True to approve, false to disapprove */\n approve: boolean;\n}\n\n/**\n * React Query mutation hook for voting for a Hive witness.\n *\n * This mutation broadcasts an account_witness_vote operation to vote for\n * or remove a vote from a witness.\n *\n * @param username - The username voting for the witness (required for broadcast)\n * @param auth - Authentication context with platform adapter and fallback configuration\n *\n * @returns React Query mutation result\n *\n * @remarks\n * **Post-Broadcast Actions:**\n * - Invalidates account data cache to show updated witness votes\n * - Invalidates witness votes cache\n *\n * **Vote Types:**\n * - approve: true - Vote for the witness\n * - approve: false - Remove your vote from the witness\n *\n * **Authority Required:**\n * - Active authority is required for witness voting\n *\n * @example\n * ```typescript\n * const witnessVoteMutation = useWitnessVote(username, {\n * adapter: myAdapter,\n * enableFallback: true,\n * fallbackChain: ['keychain', 'key', 'hivesigner']\n * });\n *\n * // Vote for a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: true\n * });\n *\n * // Remove vote from a witness\n * witnessVoteMutation.mutate({\n * witness: 'good-karma',\n * approve: false\n * });\n * ```\n */\nexport function useWitnessVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"vote\"],\n username,\n ({ witness, approve }) => [\n buildWitnessVoteOp(username!, witness, approve)\n ],\n async () => {\n // Wrap post-broadcast side-effects in try-catch to prevent propagating errors\n try {\n // Cache invalidation\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.votes(username)\n ]);\n }\n } catch (error) {\n // Log but don't rethrow - don't fail mutation due to side-effect errors\n console.warn('[useWitnessVote] Post-broadcast side-effect failed:', error);\n }\n },\n auth,\n 'active', // Use active authority for witness votes (required by blockchain)\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildWitnessProxyOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface WitnessProxyPayload {\n proxy: string;\n}\n\nexport function useWitnessProxy(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"witnesses\", \"proxy\"],\n username,\n ({ proxy }) => [\n buildWitnessProxyOp(username!, proxy)\n ],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.witnesses.proxy(),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { Witness, WitnessVotersResponse } from \"../types\";\nimport { callREST } from \"@/modules/core/hive-tx\";\nimport { QueryKeys } from \"@/modules/core\";\n\ntype WitnessPage = Witness[];\ntype WitnessCursor = number;\n\ninterface HafbeWitness {\n witness_name: string;\n rank: number;\n url: string;\n vests: string;\n votes_daily_change: string;\n voters_num: number;\n voters_num_daily_change: number;\n price_feed: number;\n bias: number;\n feed_updated_at: string;\n block_size: number;\n signing_key: string;\n version: string;\n missed_blocks: number;\n hbd_interest_rate: number;\n last_confirmed_block_num: number;\n account_creation_fee: number;\n}\n\ninterface HafbeWitnessesResponse {\n total_witnesses: number;\n total_pages: number;\n witnesses: HafbeWitness[];\n}\n\n/**\n * Map a hafbe-api witness to the SDK Witness shape so existing consumers\n * (e.g. the web app's transform()) keep working unchanged.\n */\nfunction mapRestWitness(w: HafbeWitness): Witness {\n return {\n owner: w.witness_name,\n total_missed: w.missed_blocks,\n url: w.url,\n props: {\n account_creation_fee: `${(w.account_creation_fee / 1000).toFixed(3)} HIVE`,\n account_subsidy_budget: 0,\n maximum_block_size: w.block_size,\n },\n hbd_exchange_rate: {\n base: `${w.price_feed.toFixed(3)} HBD`,\n },\n available_witness_account_subsidies: 0,\n running_version: w.version,\n signing_key: w.signing_key,\n last_hbd_exchange_update: w.feed_updated_at,\n rank: w.rank,\n vests: w.vests,\n voters_num: w.voters_num,\n voters_num_daily_change: w.voters_num_daily_change,\n price_feed: w.price_feed,\n hbd_interest_rate: w.hbd_interest_rate,\n last_confirmed_block_num: w.last_confirmed_block_num,\n };\n}\n\n/**\n * Get witnesses ordered by vote count (infinite scroll).\n * Uses the hafbe-api REST endpoint - replaces multi-call RPC assembly\n * with a single paginated call. Includes voter count, rank, and other\n * data that was previously unavailable.\n *\n * @param limit - Number of witnesses per page\n */\nexport function getWitnessesInfiniteQueryOptions(limit: number) {\n return infiniteQueryOptions<\n WitnessPage,\n Error,\n InfiniteData,\n (string | number)[],\n WitnessCursor\n >({\n queryKey: QueryKeys.witnesses.list(limit),\n initialPageParam: 1 as WitnessCursor,\n\n queryFn: async ({ pageParam }: { pageParam: WitnessCursor }) => {\n const response = (await callREST(\n \"hafbe\",\n \"/witnesses\",\n {\n \"page-size\": limit,\n page: pageParam,\n }\n )) as HafbeWitnessesResponse;\n\n return response.witnesses.map(mapRestWitness);\n },\n\n getNextPageParam: (lastPage, _allPages, lastPageParam) =>\n lastPage.length === limit ? lastPageParam + 1 : undefined,\n });\n}\n\nexport type WitnessVoterSortField =\n | \"vests\"\n | \"account_vests\"\n | \"proxied_vests\"\n | \"account_name\"\n | \"timestamp\";\n\nexport type WitnessVoterSortDirection = \"asc\" | \"desc\";\n\n/**\n * Get a single page of voters for a specific witness.\n *\n * Server-side pagination + sort: each page click fetches that page directly\n * from hafbe rather than scrolling through accumulated pages on the client.\n *\n * @param witness - Witness account name\n * @param page - 1-based page index\n * @param pageSize - Number of voters per page\n * @param sort - Field to sort by\n * @param direction - asc or desc\n */\nexport function getWitnessVotersPageQueryOptions(\n witness: string,\n page: number,\n pageSize: number,\n sort: WitnessVoterSortField = \"vests\",\n direction: WitnessVoterSortDirection = \"desc\"\n) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voters(witness, page, pageSize, sort, direction),\n queryFn: async ({ signal }) => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters\",\n {\n \"witness-name\": witness,\n \"page-size\": pageSize,\n page,\n sort,\n direction,\n },\n undefined,\n undefined,\n signal\n )) as WitnessVotersResponse;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n\n/**\n * Get total voter count for a witness.\n *\n * @param witness - Witness account name\n */\nexport function getWitnessVoterCountQueryOptions(witness: string) {\n return queryOptions({\n queryKey: QueryKeys.witnesses.voterCount(witness),\n queryFn: async () => {\n return (await callREST(\n \"hafbe\",\n \"/witnesses/{witness-name}/voters/count\",\n { \"witness-name\": witness }\n )) as number;\n },\n enabled: !!witness,\n staleTime: 60_000,\n });\n}\n","export enum PointTransactionType {\n CHECKIN = 10,\n LOGIN = 20,\n CHECKIN_EXTRA = 30,\n POST = 100,\n COMMENT = 110,\n VOTE = 120,\n REBLOG = 130,\n DELEGATION = 150,\n REFERRAL = 160,\n COMMUNITY = 170,\n TRANSFER_SENT = 998,\n TRANSFER_INCOMING = 999,\n MINTED = 991,\n /**\n * Points burned out of supply rather than moved to the treasury. Written by the\n * AI surfaces (assist, image, transcribe), which pay a real per-request vendor\n * bill, so the Points are consumed rather than parked.\n *\n * The row carries no counterparty at all, which is what distinguishes it from\n * TRANSFER_SENT: `sender` and `receiver` are both null. A refund of a burn comes\n * back as this same type with a positive amount, so read the sign rather than\n * assuming a burn is always a debit.\n */\n BURNED = 997,\n}\n","import { CONFIG, getBoundFetch, getQueryClient } from \"@/modules/core\";\nimport { EcencyAnalytics } from \"@/modules/analytics\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { getPointsQueryOptions } from \"../queries\";\nimport type { Points } from \"../types\";\n\n/**\n * POST a points claim and return the parsed JSON body.\n *\n * The endpoint normally answers with JSON, but an edge/proxy layer can\n * occasionally return a 2xx whose body is an HTML interstitial or plain text\n * (ECENCY-NEXT-1FCJ). Calling `response.json()` on that throws a bare\n * `SyntaxError` that names neither the endpoint nor the cause. Instead we check\n * the content type first and fail with a STABLE, low-cardinality message\n * (content type + status) — never the raw body — so these group as a single\n * Sentry issue instead of fragmenting on every distinct HTML page.\n */\nexport async function claimPointsRequest(\n username: string | undefined,\n accessToken: string | undefined\n) {\n if (!username) {\n throw new Error(\"[SDK][Points][Claim] – username wasn't provided\");\n }\n\n if (!accessToken) {\n throw new Error(\"[SDK][Points][Claim] – access token wasn't found\");\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n CONFIG.privateApiHost + \"/private-api/points-claim\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n }\n );\n\n // Media types are case-insensitive; normalise once and reuse in every branch.\n const contentType = (response.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n const body = await response.text();\n\n if (!response.ok) {\n if (response.status === 406) {\n try {\n return JSON.parse(body);\n } catch {\n return { message: body, code: response.status };\n }\n }\n // Only fold a short JSON error body into the message; an HTML gateway page\n // (e.g. 502/503) would otherwise fragment the Sentry group per distinct\n // page — the same problem the non-JSON guard below avoids for a 2xx body.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Points][Claim] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Points][Claim] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body);\n } catch {\n throw new Error(\n `[SDK][Points][Claim] – malformed JSON response (status ${response.status})`\n );\n }\n}\n\nexport function useClaimPoints(\n username: string | undefined,\n accessToken: string | undefined,\n onSuccess?: () => void,\n onError?: Parameters[\"0\"][\"onError\"]\n) {\n const { mutateAsync: recordActivity } = EcencyAnalytics.useRecordActivity(\n username,\n \"points-claimed\"\n );\n\n return useMutation({\n mutationFn: () => claimPointsRequest(username, accessToken),\n onError,\n onSuccess: () => {\n recordActivity();\n\n getQueryClient().setQueryData(\n getPointsQueryOptions(username).queryKey,\n (data) => {\n if (!data) {\n return data;\n }\n\n return {\n ...data,\n points: (\n parseFloat(data.points) + parseFloat(data.uPoints)\n ).toFixed(3),\n uPoints: \"0\",\n };\n }\n );\n\n onSuccess?.();\n },\n });\n}\n","// A token only counts at the start of the query or after whitespace, matching\n// the search API's parser. Unanchored, these matched inside ordinary words:\n// \"prototype:v2\" read as type=v2 and the API rejected it as an invalid type,\n// \"subcategory:hive-1\" filtered on category=hive-1 with a stray \"sub\" left as\n// required text. The boundary is captured rather than looked behind so it can\n// be put back when the token is stripped, keeping the neighbouring words apart\n// (a lookbehind would also be fine here, but this stays portable).\nconst author_re = /(^|\\s)author:([^\\s]+)/g;\nconst type_re = /(^|\\s)type:([^\\s]+)/g;\nconst category_re = /(^|\\s)category:([^\\s]+)/g;\nconst tag_re = /(^|\\s)tag:([^\\s]+)/g;\n\n// Index of the token value in a match; group 1 is the boundary.\nconst VALUE = 2;\n\nexport enum SearchType {\n ALL = \"\",\n POST = \"post\",\n COMMENT = \"comment\"\n}\n\nexport const MAX_SEARCH_TAGS = 5;\n\n// The search API applies both caps itself (see query_validator); mirrored here\n// so the client can refuse instead of turning a 400 into an empty result list.\nexport const MAX_SEARCH_QUERY_LENGTH = 100;\n\n/**\n * Both parsers match a token with /author:([^\\s]+)/, so a value containing a\n * space stops filtering at the space and the remainder silently becomes\n * required free text. Keep the first word only, which is what the API would\n * have filtered on anyway.\n */\nfunction firstToken(value: string): string {\n return value.trim().split(/\\s+/)[0] ?? \"\";\n}\n\n/**\n * Hive account names are lowercase and the API filters authors with an exact\n * term query, so \"@Demo\" has to become \"demo\" or it matches nothing.\n */\nexport function normalizeSearchAuthor(value: string): string {\n return firstToken(value).replace(/^@+/, \"\").toLowerCase();\n}\n\nexport function normalizeSearchCategory(value: string): string {\n // Leading \"#\" goes for the same reason it goes on tags: a category is matched\n // by an exact term query, and users write categories the way they write tags.\n return firstToken(value).replace(/^#+/, \"\").toLowerCase();\n}\n\n/**\n * Accepts what a user actually types (\"travel, photography\", \"#travel travel\")\n * and returns exact-match ready tags, deduped in first-seen order.\n */\nexport function normalizeSearchTags(value: string): string[] {\n const seen = new Set();\n\n return value\n .split(/[\\s,]+/)\n .map((tag) => tag.replace(/^#+/, \"\").toLowerCase())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n}\n\nexport interface SearchQueryParts {\n search?: string;\n author?: string;\n type?: SearchType;\n category?: string;\n /** Raw user input (\"a, b\") or an already split list. */\n tags?: string | string[];\n}\n\nexport interface BuiltSearchQuery {\n /** The `q` value to put in the URL. Round-trips through `SearchQuery`. */\n q: string;\n search: string;\n author: string;\n type: SearchType;\n category: string;\n tags: string[];\n}\n\n/**\n * Assembles the single `q` string that both this app and the search API parse\n * back into filters. Returns the normalized parts too, because the caller has\n * to validate the tag count and the total length before navigating.\n */\nexport function buildSearchQuery({\n search = \"\",\n author = \"\",\n type = SearchType.ALL,\n category = \"\",\n tags = []\n}: SearchQueryParts): BuiltSearchQuery {\n const normalizedSearch = search.trim().replace(/\\s+/g, \" \");\n const normalizedAuthor = normalizeSearchAuthor(author);\n const normalizedCategory = normalizeSearchCategory(category);\n const normalizedTags = normalizeSearchTags(Array.isArray(tags) ? tags.join(\",\") : tags);\n\n const parts = [normalizedSearch];\n\n if (normalizedAuthor) {\n parts.push(`author:${normalizedAuthor}`);\n }\n\n if (type) {\n parts.push(`type:${type}`);\n }\n\n if (normalizedCategory) {\n parts.push(`category:${normalizedCategory}`);\n }\n\n if (normalizedTags.length > 0) {\n // No space after the commas: a tag token ends at the first space, so\n // anything past one stops filtering and becomes required free text.\n parts.push(`tag:${normalizedTags.join(\",\")}`);\n }\n\n return {\n // Dropping the empty free text here is what keeps a filter-only query from\n // starting with a space.\n q: parts.filter((part) => part !== \"\").join(\" \"),\n search: normalizedSearch,\n author: normalizedAuthor,\n type,\n category: normalizedCategory,\n tags: normalizedTags\n };\n}\n\nexport class SearchQuery {\n public query: string = \"\";\n public search: string = \"\";\n public author: string = \"\";\n public type: SearchType = SearchType.ALL;\n public category: string = \"\";\n public tags: string[] = [];\n\n constructor(_query: string) {\n this.query = _query;\n this.search = _query;\n\n this.grabAuthor();\n this.grabType();\n this.grabCategory();\n this.grabTags();\n this.grabSearch();\n }\n\n private grab = (re: RegExp): string => {\n // @ts-ignore\n const matches = [...this.query.matchAll(re)];\n if (matches.length > 0) {\n return matches[0][VALUE].trim();\n }\n\n return \"\";\n };\n\n private grabAuthor = () => {\n this.author = this.grab(author_re);\n };\n\n private grabType = () => {\n const type = this.grab(type_re) as SearchType;\n if (Object.values(SearchType).includes(type)) {\n this.type = type as SearchType;\n }\n };\n\n private grabCategory = () => {\n this.category = this.grab(category_re);\n };\n\n private grabTags = () => {\n // Every tag: token counts, not just the first one. The API joins all of its\n // own tag: matches before splitting on commas, so reading only the first\n // token here under-reports the tags a query really applies and let a query\n // past the MAX_SEARCH_TAGS guard that the API then rejects with a 400.\n // A trailing comma (\"tag:a,\") must not yield an empty tag either - it would\n // be shown back as a phantom tag and counted against the same cap.\n const seen = new Set();\n\n this.tags = [...this.query.matchAll(tag_re)]\n .flatMap((match) => match[VALUE].split(\",\"))\n .map((tag) => tag.trim())\n .filter((tag) => {\n if (tag === \"\" || seen.has(tag)) {\n return false;\n }\n\n seen.add(tag);\n return true;\n });\n };\n\n private grabSearch = () => {\n [author_re, type_re, category_re, tag_re].forEach((r) => {\n // Put the captured boundary back, or removing a mid-query token would\n // run the words either side of it together.\n this.search = this.search.replace(r, \"$1\");\n });\n\n while (this.search.indexOf(\" \") !== -1) {\n this.search = this.search.replace(\" \", \" \");\n }\n\n this.search = this.search.trim();\n };\n}\n","export type RequestError = Error & { status?: number; data?: unknown };\n\n/**\n * Reads a response body and, when the status is not OK, throws an error that\n * keeps both the status and the parsed body.\n *\n * The search backend answers a malformed query with an explanation the user can\n * act on (\"Maximum 5 tags!\", \"Query string too long! ...\", \"Parsed query is\n * empty!\"). Dropping the body leaves callers with a bare status: they can\n * neither tell the user what to change nor tell a deterministic rejection from\n * a transient failure worth retrying.\n *\n * Module-internal on purpose - it is not part of the published SDK surface.\n */\nexport async function parseJsonResponse(\n response: Response,\n /**\n * Shape guard for a SUCCESSFUL body. JSON.parse happily accepts `null`,\n * `\"maintenance\"` and `{\"error\": \"...\"}`, none of which are the payload the\n * caller asked for, and all of which would otherwise be returned as `T` and\n * cached as valid data. Callers that have a known shape pass a guard so an\n * unexpected 200 fails here instead of at the first property access.\n */\n isValid?: (data: unknown) => boolean\n): Promise {\n const parseBody = async (): Promise => {\n // Read the body ONCE. Calling json() and then falling back to text() on the\n // same response cannot work: json() consumes the stream, so the fallback\n // always threw and the raw body of a non-JSON failure (an HTML error page\n // from a proxy) was silently lost.\n let raw: string;\n try {\n raw = await response.text();\n } catch {\n return undefined;\n }\n\n if (raw === \"\") {\n return undefined;\n }\n\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n // Raw text is a diagnostic, not a payload. On a failed response it is\n // what the caller shows or logs, but on a 2xx returning it would hand\n // back a string typed as the parsed body: callers reading `.results`\n // would see undefined and report an empty result set, and the\n // controversial/rising pager would throw on `resp.results.length`. An\n // unparseable success is a failure, so let it fall through to the throw\n // below rather than caching a string as a SearchResponse.\n return response.ok ? undefined : raw;\n }\n };\n\n const data = await parseBody();\n if (!response.ok) {\n const error = new Error(`Request failed with status ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n if (data === undefined || (isValid !== undefined && !isValid(data))) {\n throw new Error(\"Response body was empty, invalid JSON, or not the expected shape\");\n }\n\n return data as T;\n}\n\n/**\n * The contract every /search-api consumer relies on: an object carrying a\n * `results` array. Enough to keep a stray 200 from reaching `resp.results.length`.\n */\nexport function isSearchResponse(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n Array.isArray((data as { results?: unknown }).results)\n );\n}\n","import { isServer } from \"@tanstack/react-query\";\nimport type { RequestError } from \"./parse-json-response\";\n\n/**\n * The app-wide default the browser QueryClient uses. Restated because supplying\n * a `retry` callback replaces React Query's own budget rather than adding to it.\n *\n * The 0 on the server is load-bearing: server QueryClients set `retry: false`\n * globally, and these queries are prefetched during SSR, so a flat 3 would\n * resurrect SSR retries against a single-region backend.\n */\nconst MAX_RETRIES = isServer ? 0 : 3;\n\n/**\n * Shared retry rule for every /search-api call.\n *\n * A 4xx is the backend rejecting the query itself (too many tags, over the\n * length cap, nothing left to search once the filters are parsed out).\n * Repeating it repeats the same answer, so the only effect is four requests\n * over several seconds before the UI can say what to change.\n *\n * 408 and 429 are the exceptions: they describe when the request arrived rather\n * than what it contained, and backing off is what resolves them. A client-side\n * timeout aborts the fetch and carries no status at all, so it falls through to\n * the normal budget like any other transport failure.\n */\nexport function searchRetryPolicy(failureCount: number, error: Error): boolean {\n const { status } = error as RequestError;\n const isTransient = status === 408 || status === 429;\n\n if (status !== undefined && status >= 400 && status < 500 && !isTransient) {\n return false;\n }\n\n return failureCount < MAX_RETRIES;\n}\n","import { InfiniteData, infiniteQueryOptions, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function searchQueryOptions(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number\n) {\n return queryOptions({\n queryKey: QueryKeys.search.results(q, sort, hideLow, since, scroll_id, votes),\n queryFn: async ({ signal }) => {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (scroll_id) data.scroll_id = scroll_id;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n retry: searchRetryPolicy,\n });\n}\n\ntype PageParam = {\n sid: string | undefined;\n hasNextPage: boolean;\n};\n\nexport function getControversialRisingInfiniteQueryOptions(\n what: string,\n tag: string,\n enabled = true\n) {\n return infiniteQueryOptions<\n SearchResponse,\n Error,\n InfiniteData,\n (string | number)[],\n PageParam\n >({\n queryKey: QueryKeys.search.controversialRising(what, tag),\n initialPageParam: { sid: undefined, hasNextPage: true } as PageParam,\n\n queryFn: async ({ pageParam, signal }: { pageParam: PageParam; signal: AbortSignal }) => {\n if (!pageParam.hasNextPage) {\n return {\n hits: 0,\n took: 0,\n results: [],\n };\n }\n\n let sinceDate: Date | undefined;\n const now = new Date();\n\n switch (tag) {\n case \"today\":\n sinceDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);\n break;\n case \"week\":\n sinceDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case \"month\":\n sinceDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);\n break;\n case \"year\":\n sinceDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);\n break;\n default:\n sinceDate = undefined;\n }\n\n const q = \"* type:post\";\n const sort = what === \"rising\" ? \"children\" : what;\n const since = sinceDate ? sinceDate.toISOString().split(\".\")[0] : undefined;\n const hideLow = \"0\";\n const votes = tag === \"today\" ? 50 : 200;\n\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) data.since = since;\n if (pageParam.sid) data.scroll_id = pageParam.sid;\n if (votes) data.votes = votes;\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body) instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n\n getNextPageParam: (resp: SearchResponse): PageParam => {\n return {\n sid: resp?.scroll_id,\n hasNextPage: resp.results.length > 0,\n };\n },\n\n enabled,\n retry: searchRetryPolicy,\n });\n}\n","import { CONFIG, INTERNAL_API_TIMEOUT_MS, getBoundFetch, withTimeoutSignal } from \"@/modules/core\";\nimport { SearchResponse } from \"./types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"./parse-json-response\";\n\nexport async function search(\n q: string,\n sort: string,\n hideLow: string,\n since?: string,\n scroll_id?: string,\n votes?: number,\n signal?: AbortSignal\n): Promise {\n const data: {\n q: string;\n sort: string;\n hide_low: string;\n since?: string;\n scroll_id?: string;\n votes?: number;\n } = { q, sort, hide_low: hideLow };\n\n if (since) {\n data.since = since;\n }\n if (scroll_id) {\n data.scroll_id = scroll_id;\n }\n if (votes) {\n data.votes = votes;\n }\n\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(data),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function similar(\n params: {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n tags?: string[];\n since?: string;\n },\n signal?: AbortSignal,\n timeoutMs: number = INTERNAL_API_TIMEOUT_MS\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/similar\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(params),\n signal: withTimeoutSignal(timeoutMs, signal),\n });\n\n return parseJsonResponse(response, isSearchResponse);\n}\n\nexport async function searchPath(q: string, signal?: AbortSignal): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n const data = await parseJsonResponse(response, Array.isArray);\n return data?.length > 0 ? data : [q];\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { similar } from \"../requests\";\nimport { SearchResult } from \"../types/search-response\";\n\n// Without a recency window the backend ranks across the entire historical\n// index and surfaces years-old posts. Constrain suggestions to the last\n// ~6 months so related posts stay fresh (it also bounds the backend's\n// more_like_this candidate set, which is what keeps it fast).\nconst SIMILAR_ENTRIES_SINCE_MS = 182 * 24 * 60 * 60 * 1000;\n\n// How many results the suggestions strip renders at most.\nconst SIMILAR_ENTRIES_TARGET = 4;\n\n// more_like_this only extracts a handful of significant terms, so an excerpt is\n// enough signal and keeps the request payload small.\nconst SIMILAR_ENTRIES_BODY_LIMIT = 3000;\n\n// On the server the prefetch sits on the entry-page render path, and the search\n// backend is single-region (EU) — so anything slower than this stalls SSR for a\n// non-essential \"related posts\" strip. Keep the SSR cap short and let the strip\n// fall back to a client fetch (only that render misses the in-HTML strip; it's\n// ISR-cached anyway). Do NOT raise this — 2s is the SSR budget.\nconst SIMILAR_ENTRIES_SSR_TIMEOUT_MS = 2000;\n\n// The client fetch doesn't block paint, so it previously had no cap and fell\n// through to the SDK's generic INTERNAL_API_TIMEOUT_MS (10s; CF's worker further\n// truncates at ~8s). Combined with React Query's default client retry (3×), a\n// /search-api/similar outage turned this best-effort strip into a multi-second\n// post-onload tail (observed as a ~29s \"fully loaded\" in GTmetrix). Cap the\n// client call short and disable retry (below) so a degraded backend just hides\n// the strip quickly instead of churning.\nconst SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS = 4000;\n\n// The strip is hidden below this many results. A lone suggestion looks\n// sparse. Exported so the web component shares one threshold (filter == render).\nexport const SIMILAR_ENTRIES_MIN_RENDER = 2;\n\n// Strip markdown image/link/URL noise before truncating, so more_like_this\n// keys on prose terms instead of image-CDN domains and file hashes (which\n// rarely match the index's sanitized body and just waste the term budget).\nfunction toMltExcerpt(body: string, limit: number): string {\n return body\n .replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, \" \") // markdown images\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\") // markdown links -> keep link text\n .replace(/<[^>]+>/g, \" \") // html tags\n .replace(/https?:\\/\\/\\S+/g, \" \") // bare URLs\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, limit);\n}\n\n// Compact deterministic fingerprint (djb2) of the MLT inputs. Folded into the\n// cache key so an edited post (title/tags/body changed) refetches instead of\n// serving stale recommendations under the same author/permlink. Deterministic\n// so the SSR prefetch and the client compute the same key from the same entry.\nfunction fingerprint(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h >>> 0).toString(36);\n}\n\ninterface Entry {\n author: string;\n permlink: string;\n title?: string;\n body?: string;\n json_metadata?: {\n // Hive's json_metadata is user-controlled and untyped on-chain: `tags` is\n // usually a string[] but some posts store it as a bare string (or other\n // junk). Typed as unknown on purpose so callers can't assume an array —\n // it's narrowed with a runtime guard below.\n tags?: unknown;\n };\n}\n\nexport function getSimilarEntriesQueryOptions(entry: Entry) {\n const title = entry.title ?? \"\";\n // `?? []` only guards null/undefined; a non-array tags value (e.g. a bare\n // string from json_metadata) slips through and crashes `.filter` — which\n // took down the entry-page SSR prefetch (Sentry ECENCY-NEXT-1FMA). Guard on\n // Array.isArray so only real arrays reach the filter.\n const rawTags = entry.json_metadata?.tags;\n const tags = (Array.isArray(rawTags) ? rawTags : []).filter(\n (tag): tag is string => typeof tag === \"string\" && tag !== \"\"\n );\n const body = toMltExcerpt(entry.body ?? \"\", SIMILAR_ENTRIES_BODY_LIMIT);\n const contentKey = fingerprint(`${title}|${tags.join(\",\")}|${body}`);\n\n return queryOptions({\n queryKey: QueryKeys.search.similarEntries(entry.author, entry.permlink, contentKey),\n queryFn: async ({ signal }) => {\n // Naive `YYYY-MM-DDTHH:mm:ss` (no `Z`) matches the search-api date\n // contract used elsewhere; a <14h skew on a 182-day boundary is immaterial.\n const since = new Date(Date.now() - SIMILAR_ENTRIES_SINCE_MS).toISOString().slice(0, 19);\n\n // Elasticsearch more_like_this recommendations: content-based \"related\n // posts\" ranked by shared significant terms in title/body/tags, scoped\n // to the recency window. The backend already excludes the source author,\n // spam and nsfw.\n const response = await similar(\n {\n author: entry.author,\n permlink: entry.permlink,\n title,\n body,\n tags,\n since\n },\n signal,\n // Short cap server-side so a slow cross-region call can't stall SSR;\n // a slightly longer (but still bounded) cap client-side so a degraded\n // backend can't hang the request on the SDK's generic 8s timeout.\n typeof window === \"undefined\"\n ? SIMILAR_ENTRIES_SSR_TIMEOUT_MS\n : SIMILAR_ENTRIES_CLIENT_TIMEOUT_MS\n );\n\n // Light client guard mirroring the render contract: never the source\n // post, never nsfw, one per author, capped at the render target.\n const collected: SearchResult[] = [];\n const seenAuthors = new Set();\n for (const r of response.results) {\n if (collected.length >= SIMILAR_ENTRIES_TARGET) break;\n if (r.permlink === entry.permlink) continue;\n if ((r.tags ?? []).indexOf(\"nsfw\") !== -1) continue;\n if (seenAuthors.has(r.author)) continue;\n seenAuthors.add(r.author);\n collected.push(r);\n }\n\n return collected;\n },\n // The entry page server-prefetches this query and dehydrates it. Without a\n // staleTime, React Query treats the hydrated data as stale and refetches on\n // mount — issuing a *redundant* /search-api/similar XHR right after\n // hydration even though SSR already provided the data. That refetch was the\n // long post-onload tail in the waterfall (held open to the client timeout),\n // inflating GTmetrix \"Fully Loaded\" while the visible strip was already\n // populated from SSR. A staleTime makes the hydrated data fresh so the\n // client skips that refetch; if SSR delivered nothing (empty cache), the\n // client still fetches. Recommendations are stable per post (and the cache\n // key is content-fingerprinted), so 5 min matches the page's ISR cadence.\n staleTime: 5 * 60 * 1000,\n // Best-effort suggestions strip — never retry-storm a degraded backend.\n // The web QueryClient only disables retries on the server; the browser\n // client keeps React Query's default retry (3×) — and other SDK consumers\n // (e.g. mobile) may too — so pin retry:false here to cover every caller.\n retry: false\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { getProfiles } from \"@/modules/bridge\";\nimport { Profile } from \"@/modules/accounts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchAccountQueryOptions(q: string, limit = 5) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.account(normalized, limit),\n queryFn: async (): Promise => {\n const usernames = (await callRPC(\"condenser_api.lookup_accounts\", [\n normalized,\n limit,\n ])) as string[];\n\n if (usernames.length === 0) {\n return [];\n }\n\n return getProfiles(usernames);\n },\n enabled: !!normalized,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"@/modules/core\";\nimport { TrendingTag } from \"@/modules/posts/types\";\nimport { callRPC } from \"@/modules/core/hive-tx\";\n\nexport function getSearchTopicsQueryOptions(q: string, limit = 10) {\n const normalized = q.trim();\n\n return queryOptions({\n queryKey: QueryKeys.search.topics(normalized, limit),\n queryFn: async (): Promise => {\n const tags = (await callRPC(\"condenser_api.get_trending_tags\", [\n normalized,\n limit + 1,\n ])) as TrendingTag[];\n\n return tags\n .map((t) => t.name)\n .filter((name) => name !== \"\" && !name.startsWith(\"hive-\"))\n .slice(0, limit);\n },\n enabled: !!normalized,\n });\n}\n","import { infiniteQueryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, INTERNAL_API_TIMEOUT_MS, withTimeoutSignal, QueryKeys } from \"@/modules/core\";\nimport { SearchResponse } from \"../types/search-response\";\nimport { isSearchResponse, parseJsonResponse } from \"../parse-json-response\";\nimport { searchRetryPolicy } from \"../retry-policy\";\n\nexport function getSearchApiInfiniteQueryOptions(\n q: string,\n sort: string,\n hideLow: boolean,\n since?: string,\n votes?: number,\n includeNsfw?: boolean\n) {\n return infiniteQueryOptions({\n queryKey: QueryKeys.search.api(q, sort, hideLow, since, votes, includeNsfw),\n queryFn: async ({ pageParam, signal }: { pageParam: string | undefined; signal: AbortSignal }) => {\n interface SearchApiPayload {\n q: string;\n sort: string;\n hide_low: boolean;\n since?: string;\n scroll_id?: string;\n votes?: number;\n include_nsfw?: number;\n }\n\n const payload: SearchApiPayload = { q, sort, hide_low: hideLow };\n\n if (since) {\n payload.since = since;\n }\n if (pageParam) {\n payload.scroll_id = pageParam;\n }\n if (votes !== undefined) {\n payload.votes = votes;\n }\n if (includeNsfw) {\n payload.include_nsfw = 1;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify(payload),\n signal: withTimeoutSignal(INTERNAL_API_TIMEOUT_MS, signal),\n });\n\n // Keeps the backend's own explanation of a rejected query on the error\n // (status + body), instead of collapsing it to a status code.\n return parseJsonResponse(response, isSearchResponse);\n },\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage: SearchResponse) => lastPage?.scroll_id,\n enabled: !!q,\n retry: searchRetryPolicy,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"@/modules/core\";\n\nexport function getSearchPathQueryOptions(q: string) {\n return queryOptions({\n queryKey: [\"search\", \"path\", q],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/search-api/search-path\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Ecency-Client\": CONFIG.clientId,\n },\n body: JSON.stringify({ q }),\n });\n\n if (!response.ok) {\n throw new Error(`Search path failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (data?.length > 0) {\n return data as string[];\n }\n\n return [q];\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { SupportSettings } from \"../types\";\n\n/**\n * Fetch the active user's Support Ecency settings. The username is resolved\n * server-side from the validated `code`, so only the code is sent. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached. Exported for\n * unit testing; the query options below wrap it.\n */\nexport async function getSupportSettingsRequest(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to fetch support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Query options for the active user's Support Ecency settings\n * (beneficiary percent + curation holdback percent). Zeros mean both\n * opt-ins are off; the backend returns zeros when no row exists.\n */\nexport function getSupportSettingsQueryOptions(\n username: string | undefined,\n code: string | undefined\n) {\n const name = username?.replace(\"@\", \"\");\n\n return queryOptions({\n queryKey: QueryKeys.support.settings(name),\n queryFn: () => {\n if (!code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return getSupportSettingsRequest(code);\n },\n enabled: !!name && !!code,\n });\n}\n","import { CONFIG, getBoundFetch, QueryKeys } from \"@/modules/core\";\nimport { QueryClient, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { SupportSettings, UpdateSupportSettingsPayload } from \"../types\";\n\n/**\n * POST a Support Ecency settings update. Both percents are integers within\n * 0..100 (0 = off); the gateway rejects anything else with a 400. Throws on a\n * non-2xx with the server's `.status` + parsed `.data` attached so the caller\n * can surface the plain validation message. Exported for unit testing; the\n * hook below wraps it.\n */\nexport async function updateSupportSettingsRequest(\n code: string,\n payload: UpdateSupportSettingsPayload\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/private-api/support-settings-update\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n code,\n beneficiary_percent: payload.beneficiary_percent,\n curation_percent: payload.curation_percent,\n }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n // non-JSON error body; fall through with status only\n }\n const message =\n (data as { message?: string })?.message ??\n `Failed to update support settings: ${response.status}`;\n const err = new Error(message) as Error & { status?: number; data?: unknown };\n err.status = response.status;\n err.data = data;\n throw err;\n }\n\n return (await response.json()) as SupportSettings;\n}\n\n/**\n * Sync the settings cache after a successful update: seed the fresh server\n * response and invalidate so any active observers refetch. Exported for unit\n * testing; `useUpdateSupportSettings` calls it from `onSuccess`.\n */\nexport function applySupportSettingsUpdate(\n queryClient: QueryClient,\n username: string,\n data: SupportSettings\n) {\n queryClient.setQueryData(QueryKeys.support.settings(username), data);\n return queryClient.invalidateQueries({ queryKey: QueryKeys.support.settings(username) });\n}\n\n/**\n * Update the user's voluntary Support Ecency opt-ins (post beneficiary percent\n * and curation holdback percent). On success the settings query is refreshed\n * so every surface (publish dialog, settings card, injection hooks) sees the\n * new preference.\n */\nexport function useUpdateSupportSettings(\n username: string | undefined,\n code: string | undefined\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"support\", \"settings-update\", name],\n mutationFn: async (payload: UpdateSupportSettingsPayload) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Support] missing auth\");\n }\n return updateSupportSettingsRequest(code, payload);\n },\n onSuccess(data) {\n if (name) {\n applySupportSettingsUpdate(queryClient, name, data);\n }\n },\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getBoostPlusPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boost-plus-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\n/**\n * RC top-up pricing: duration -> Points cost tiers, served by the ePoints\n * backend via the private API. Reuses the {@link PromotePrice} shape\n * ({ duration, price }).\n */\nexport function getRcDelegationPricesQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-prices\"],\n queryFn: async () => {\n if (!accessToken) {\n return [];\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation prices: ${response.status}`);\n }\n\n return (await response.json()) as PromotePrice[];\n },\n staleTime: Infinity,\n enabled: !!accessToken,\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface RcDelegationActive {\n user: string;\n expires: Date;\n}\n\n/**\n * The active (ON) RC top-up for a user, if any. Lets the UI block a duplicate\n * purchase up front (only one RC top-up is allowed at a time). Returns null\n * when the user has no active top-up.\n */\nexport function getRcDelegationActiveQueryOptions(username: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"rc-delegation-active\", username],\n queryFn: async (): Promise => {\n if (!accessToken || !username) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/rc-delegation-active\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ code: accessToken, username })\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch RC delegation active: ${response.status}`);\n }\n\n const responseData = (await response.json()) as { user?: string; expires?: string };\n\n return responseData && responseData.expires && responseData.user\n ? { user: responseData.user, expires: new Date(responseData.expires) }\n : null;\n },\n enabled: !!username && !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\nimport type { PromotePrice } from \"../types\";\n\nexport function getPromotePriceQueryOptions(accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"promote-price\"],\n queryFn: async () => {\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/promote-price\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch promote prices: ${response.status}`);\n }\n\n return await response.json() as PromotePrice[];\n },\n enabled: !!accessToken\n });\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG } from \"../../core\";\n\nexport interface BoostPlusAccountPrice {\n account: string;\n expires: Date;\n}\n\nexport function getBoostPlusAccountPricesQueryOptions(account: string, accessToken: string) {\n return queryOptions({\n queryKey: [\"promotions\", \"boost-plus-accounts\", account],\n queryFn: async (): Promise => {\n if (!accessToken || !account) {\n return null;\n }\n\n const response = await fetch(CONFIG.privateApiHost + \"/private-api/boosted-plus-account\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code: accessToken, account }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch boost plus account prices: ${response.status}`);\n }\n\n const responseData = await response.json() as {\n expires: string;\n account: string;\n };\n\n return responseData\n ? {\n account: responseData.account,\n expires: new Date(responseData.expires)\n }\n : null;\n },\n enabled: !!account && !!accessToken\n });\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildBoostPlusOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface BoostPlusPayload {\n account: string;\n duration: number;\n}\n\nexport function useBoostPlus(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"boost-plus\"],\n username,\n ({ account, duration }) => [\n buildBoostPlusOp(username!, account, duration)\n ],\n async (_data, { account }) => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.promotions.boostPlusAccounts(account),\n ]);\n }\n },\n auth,\n 'active',\n { broadcastMode }\n );\n}\n","import { useBroadcastMutation, QueryKeys } from \"@/modules/core\";\nimport type { BroadcastMode } from \"@/modules/core\";\nimport { buildRcDelegationOp } from \"@/modules/operations/builders\";\nimport type { AuthContextV2 } from \"@/modules/core/types\";\n\nexport interface RcDelegationPayload {\n duration: number;\n}\n\n/**\n * Buys a short-term, RC-only delegation (RC top-up) for the active user, paid\n * with Ecency Points. Mirrors {@link useBoostPlus} but is RC-only (no Hive\n * Power / voting power transferred). Invalidates the user's account + RC caches\n * so the new RC shows up once the relay delegation lands.\n */\nexport function useRcDelegation(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n [\"promotions\", \"rc-delegation\"],\n username,\n ({ duration }) => [buildRcDelegationOp(username!, duration)],\n async () => {\n if (auth?.adapter?.invalidateQueries) {\n await auth.adapter.invalidateQueries([\n QueryKeys.accounts.full(username),\n QueryKeys.resourceCredits.account(username!),\n [\"promotions\", \"rc-delegation-active\", username]\n ]);\n }\n },\n auth,\n \"active\",\n { broadcastMode }\n );\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport { HsTokenRenewResponse } from \"./types\";\n\ntype RequestError = Error & { status?: number; data?: unknown };\n\nexport async function hsTokenRenew(code: string): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(CONFIG.privateApiHost + \"/auth-api/hs-token-refresh\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ code }),\n });\n\n if (!response.ok) {\n let data: unknown = undefined;\n try {\n data = await response.json();\n } catch {\n data = undefined;\n }\n const error = new Error(`Failed to refresh token: ${response.status}`) as RequestError;\n error.status = response.status;\n error.data = data;\n throw error;\n }\n\n const data = (await response.json()) as HsTokenRenewResponse;\n return data;\n}\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { QueryKeys } from \"../../core\";\n\nconst BAD_ACTORS_URL =\n \"https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt\";\n\nexport function getBadActorsQueryOptions() {\n return queryOptions({\n queryKey: QueryKeys.badActors.list(),\n queryFn: async ({ signal }) => {\n const response = await fetch(BAD_ACTORS_URL, { signal });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch bad actors list: ${response.status}`);\n }\n\n const text = await response.text();\n return new Set(text.split(\"\\n\").filter(Boolean));\n },\n staleTime: 24 * 60 * 60 * 1000,\n /**\n * Deliberately left unbounded, including under SSR.\n *\n * `Infinity` is the one value that schedules no gc timer at all —\n * `isValidTimeout` in query-core rejects non-finite timeouts, so\n * `scheduleGc` is a no-op. With no timer there is no GC root, and on a\n * per-request client the entry dies with the request that made it.\n * Replacing it with a finite window would *create* a timer that retains the\n * Query and, through it, that request's whole QueryCache — strictly worse\n * here than leaving it alone.\n */\n gcTime: Infinity\n });\n}\n","export const POLLS_PROTOCOL_VERSION = 1.1;\n\nexport enum PollPreferredInterpretation {\n NUMBER_OF_VOTES = \"number_of_votes\",\n TOKENS = \"tokens\",\n}\n\nexport interface PollChoiceVotes {\n total_votes: number;\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied: number | null;\n}\n\nexport interface PollChoice {\n choice_num: number;\n choice_text: string;\n votes?: PollChoiceVotes;\n}\n\nexport interface PollVoter {\n name: string;\n choices: number[];\n hive_hp?: number;\n hive_proxied_hp?: number;\n hive_hp_incl_proxied?: number;\n}\n\nexport interface PollStats {\n total_voting_accounts_num: number;\n total_hive_hp?: number;\n total_hive_proxied_hp?: number;\n total_hive_hp_incl_proxied: number | null;\n}\n\nexport interface Poll {\n author: string;\n permlink: string;\n question: string;\n poll_choices: PollChoice[];\n poll_voters?: PollVoter[];\n poll_stats?: PollStats;\n poll_trx_id: string;\n status: string;\n end_time: string;\n preferred_interpretation: PollPreferredInterpretation | string;\n max_choices_voted: number;\n filter_account_age_days: number;\n protocol_version: number;\n created: string;\n post_title: string;\n post_body: string;\n parent_permlink: string;\n tags: string[];\n image: unknown[];\n token?: string | null;\n community_membership?: string[];\n allow_vote_changes?: boolean;\n ui_hide_res_until_voted?: boolean;\n platform?: string;\n}\n\nexport function mapMetaChoicesToPollChoices(metaChoices: string[]): PollChoice[] {\n if (!metaChoices) {\n return [];\n }\n\n return metaChoices.map((choice, index) => ({\n choice_num: index + 1,\n choice_text: choice,\n votes: {\n total_votes: 0,\n hive_hp: 0,\n hive_proxied_hp: 0,\n hive_hp_incl_proxied: 0,\n },\n }));\n}\n","import { isServer, queryOptions } from \"@tanstack/react-query\";\nimport { CONFIG, QueryKeys, SERVER_GC_TIME_MS } from \"@/modules/core\";\nimport { getBoundFetch } from \"@/modules/core/utils\";\nimport type { Poll, PollChoice, PollVoter, PollStats } from \"../types\";\n\nfunction normalizePoll(raw: Record): Poll {\n const pollChoices = (raw.poll_choices as Record[] | undefined) ?? [];\n const pollVoters = (raw.poll_voters as Record[] | undefined) ?? [];\n const rawStats = raw.poll_stats as Record | undefined;\n\n const choices: PollChoice[] = pollChoices.map((c) => {\n const votes = c.votes as Record | undefined;\n return {\n choice_num: (c.choice_num as number) ?? 0,\n choice_text: (c.choice_text as string) ?? \"\",\n votes: votes\n ? {\n total_votes: (votes.total_votes as number) ?? 0,\n hive_hp: votes.hive_hp as number | undefined,\n hive_proxied_hp: votes.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: (votes.hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined,\n };\n });\n\n const voters: PollVoter[] = pollVoters.map((v) => ({\n name: (v.name as string) ?? \"\",\n choices: (v.choices as number[]) ?? [],\n hive_hp: v.hive_hp as number | undefined,\n hive_proxied_hp: v.hive_proxied_hp as number | undefined,\n hive_hp_incl_proxied: v.hive_hp_incl_proxied as number | undefined,\n }));\n\n const stats: PollStats | undefined = rawStats\n ? {\n total_voting_accounts_num: (rawStats.total_voting_accounts_num as number) ?? 0,\n total_hive_hp: rawStats.total_hive_hp as number | undefined,\n total_hive_proxied_hp: rawStats.total_hive_proxied_hp as number | undefined,\n total_hive_hp_incl_proxied: (rawStats.total_hive_hp_incl_proxied as number | null) ?? null,\n }\n : undefined;\n\n return {\n author: (raw.author as string) ?? \"\",\n permlink: (raw.permlink as string) ?? \"\",\n question: (raw.question as string) ?? \"\",\n poll_choices: choices,\n poll_voters: voters,\n poll_stats: stats,\n poll_trx_id: (raw.poll_trx_id as string) ?? \"\",\n status: (raw.status as string) ?? \"\",\n end_time: (raw.end_time as string) ?? \"\",\n preferred_interpretation: (raw.preferred_interpretation as string) ?? \"number_of_votes\",\n max_choices_voted: (raw.max_choices_voted as number) ?? 1,\n filter_account_age_days: (raw.filter_account_age_days as number) ?? 0,\n protocol_version: (raw.protocol_version as number) ?? 0,\n created: (raw.created as string) ?? \"\",\n post_title: (raw.post_title as string) ?? \"\",\n post_body: (raw.post_body as string) ?? \"\",\n parent_permlink: (raw.parent_permlink as string) ?? \"\",\n tags: (raw.tags as string[]) ?? [],\n image: (raw.image as unknown[]) ?? [],\n token: raw.token as string | null | undefined,\n community_membership: raw.community_membership as string[] | undefined,\n allow_vote_changes: raw.allow_vote_changes as boolean | undefined,\n ui_hide_res_until_voted: (raw.ui_hide_res_until_voted as boolean | undefined) ?? false,\n platform: raw.platform as string | undefined,\n };\n}\n\nexport function getPollQueryOptions(\n author: string | undefined,\n permlink: string | undefined\n) {\n return queryOptions({\n queryKey: QueryKeys.polls.details(author ?? \"\", permlink ?? \"\"),\n enabled: !!author && !!permlink,\n // Long in a browser, where a poll is cheap to keep and often revisited;\n // bounded during SSR, where holding it also holds that request's whole\n // cache. See SERVER_GC_TIME_MS.\n gcTime: isServer ? SERVER_GC_TIME_MS : 30 * 60 * 1000,\n queryFn: async (): Promise => {\n if (!author || !permlink) {\n throw new Error(\"[SDK][Polls] – missing author or permlink\");\n }\n\n const fetchApi = getBoundFetch();\n const url = `${CONFIG.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(author)}&permlink=eq.${encodeURIComponent(permlink)}`;\n const response = await fetchApi(url);\n\n if (!response.ok) {\n throw new Error(`[SDK][Polls] – fetch failed: ${response.status}`);\n }\n\n const data = await response.json();\n\n if (!Array.isArray(data) || !data[0]) {\n throw new Error(\"[SDK][Polls] – no poll data found\");\n }\n\n return normalizePoll(data[0]);\n },\n });\n}\n","import { QueryKeys, useBroadcastMutation } from \"@/modules/core\";\nimport type { BroadcastMode, AuthContextV2 } from \"@/modules/core\";\n\nexport interface PollVotePayload {\n pollTrxId: string;\n choices: number[];\n}\n\nexport function usePollVote(\n username: string | undefined,\n auth?: AuthContextV2,\n broadcastMode?: BroadcastMode\n) {\n return useBroadcastMutation(\n QueryKeys.polls.vote(),\n username ?? \"\",\n ({ pollTrxId, choices }) => {\n if (!username) {\n throw new Error(\"[SDK][Polls] Cannot vote without an authenticated username\");\n }\n return [\n [\n \"custom_json\",\n {\n id: \"polls\",\n required_auths: [],\n required_posting_auths: [username],\n json: JSON.stringify({\n poll: pollTrxId,\n action: \"vote\",\n choices,\n }),\n },\n ],\n ];\n },\n undefined,\n auth,\n \"posting\",\n { broadcastMode: broadcastMode ?? \"async\" }\n );\n}\n"]} \ No newline at end of file diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 82cb57c592..1c7d3468c7 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,7 +1,7 @@ { "name": "@ecency/sdk", "private": false, - "version": "2.3.83", + "version": "2.3.84", "description": "Ecency SDK", "repository": { "type": "git", diff --git a/packages/sdk/src/modules/core/index.ts b/packages/sdk/src/modules/core/index.ts index 593e97cb19..7a5164fe74 100644 --- a/packages/sdk/src/modules/core/index.ts +++ b/packages/sdk/src/modules/core/index.ts @@ -8,3 +8,4 @@ export * from "./queries"; export * from "./query-keys"; export * from "./types"; export * from "./utils"; +export * from "./utf8"; diff --git a/packages/sdk/src/modules/core/query-keys.ts b/packages/sdk/src/modules/core/query-keys.ts index 28c4766426..07b4b4e4af 100644 --- a/packages/sdk/src/modules/core/query-keys.ts +++ b/packages/sdk/src/modules/core/query-keys.ts @@ -542,6 +542,7 @@ export const QueryKeys = { account: (username: string) => ["resource-credits", "account", username], stats: () => ["resource-credits", "stats"], + resourceParams: () => ["resource-credits", "resource-params"], }, // =========================================================================== diff --git a/packages/sdk/src/modules/core/utf8.ts b/packages/sdk/src/modules/core/utf8.ts new file mode 100644 index 0000000000..0b8405b81c --- /dev/null +++ b/packages/sdk/src/modules/core/utf8.ts @@ -0,0 +1,42 @@ +/** + * UTF-8 byte length of a string. + * + * `TextEncoder` is missing on some runtimes the SDK ships to (React Native / + * Hermes), and `String.length` is NOT a substitute: it counts UTF-16 code + * units, so anything non-ASCII is undercounted. Where that number feeds an RC + * estimate, undercounting means telling someone a post is affordable when the + * chain will reject it. + */ +export function utf8ByteLength(value: string): number { + if (typeof TextEncoder !== "undefined") { + return new TextEncoder().encode(value).length; + } + + let bytes = 0; + for (let i = 0; i < value.length; i++) { + const c = value.charCodeAt(i); + if (c < 0x80) { + bytes += 1; + } else if (c < 0x800) { + bytes += 2; + } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < value.length) { + // surrogate pair encodes as four bytes + i++; + bytes += 4; + } else { + bytes += 3; + } + } + return bytes; +} + +/** Byte length of Hive's unsigned LEB128 varint for `value`. */ +export function varintByteLength(value: number): number { + let count = 0; + let remaining = value; + do { + count++; + remaining >>>= 7; + } while (remaining > 0); + return count; +} diff --git a/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.spec.ts b/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.spec.ts new file mode 100644 index 0000000000..23e32d8cb9 --- /dev/null +++ b/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.spec.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { getRcResourceParamsQueryOptions } from "./get-rc-resource-params-query-options"; +import { QueryKeys } from "@/modules/core"; + +describe("getRcResourceParamsQueryOptions", () => { + const options = getRcResourceParamsQueryOptions(); + + it("uses the shared query key rather than a literal", () => { + expect(options.queryKey).toEqual(QueryKeys.resourceCredits.resourceParams()); + }); + + /** + * Regression: gcTime and staleTime were both Infinity. Infinite gcTime is + * correct, it is the one value that schedules no timer and so cannot hold a + * request's cache open on the server. Infinite staleTime is not: a + * long-lived session would keep pricing RC with pre-hardfork coefficients + * indefinitely, and a wrong estimate here tells someone a post is affordable + * when the chain will reject it. + */ + it("schedules no gc timer, so it cannot pin a server request's cache", () => { + expect(options.gcTime).toBe(Infinity); + }); + + it("keeps a bounded staleTime so hardfork changes are picked up", () => { + expect(Number.isFinite(options.staleTime)).toBe(true); + expect(options.staleTime).toBeGreaterThan(0); + }); + + it("does not refetch so often that it is chatty", () => { + // Params change at a hardfork, so a day is the intent, not minutes. + expect(options.staleTime).toBeGreaterThanOrEqual(60 * 60 * 1000); + }); +}); diff --git a/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts b/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts new file mode 100644 index 0000000000..36e8a20fe8 --- /dev/null +++ b/packages/sdk/src/modules/resource-credits/queries/get-rc-resource-params-query-options.ts @@ -0,0 +1,27 @@ +import { queryOptions } from "@tanstack/react-query"; +import { callRPC } from "@/modules/core/hive-tx"; +import { QueryKeys } from "@/modules/core"; +import type { RcResourceParams } from "../types/resource-params"; + +/** + * Curve coefficients and sizing constants used to price resource usage. + * + * These only change at a hardfork, so the entry is kept for the session: + * `gcTime: Infinity` is the one value that schedules no gc timer at all, so it + * does not hold a request's query cache open on the server the way a long + * finite window would. + * + * `staleTime` stays bounded on purpose. Making it infinite too would mean a + * long-lived session keeps pricing with pre-hardfork coefficients forever, + * quietly producing wrong RC estimates with no way to recover short of a + * reload. A day is long enough that this is effectively never refetched, and + * short enough that a hardfork corrects itself. + */ +export function getRcResourceParamsQueryOptions() { + return queryOptions({ + queryKey: QueryKeys.resourceCredits.resourceParams(), + staleTime: 24 * 60 * 60 * 1000, + gcTime: Infinity, + queryFn: async () => (await callRPC("rc_api.get_resource_params", {})) as RcResourceParams + }); +} diff --git a/packages/sdk/src/modules/resource-credits/queries/index.ts b/packages/sdk/src/modules/resource-credits/queries/index.ts index 2a6a91faf8..d2ff697492 100644 --- a/packages/sdk/src/modules/resource-credits/queries/index.ts +++ b/packages/sdk/src/modules/resource-credits/queries/index.ts @@ -1,2 +1,3 @@ export * from "./get-rc-stats-query-options"; export * from "./get-account-rc-query-options"; +export * from "./get-rc-resource-params-query-options"; diff --git a/packages/sdk/src/modules/resource-credits/types/index.ts b/packages/sdk/src/modules/resource-credits/types/index.ts index 211e8756df..5e603803f8 100644 --- a/packages/sdk/src/modules/resource-credits/types/index.ts +++ b/packages/sdk/src/modules/resource-credits/types/index.ts @@ -1 +1,2 @@ export * from "./stats"; +export * from "./resource-params"; diff --git a/packages/sdk/src/modules/resource-credits/types/resource-params.ts b/packages/sdk/src/modules/resource-credits/types/resource-params.ts new file mode 100644 index 0000000000..8af0ab8165 --- /dev/null +++ b/packages/sdk/src/modules/resource-credits/types/resource-params.ts @@ -0,0 +1,65 @@ +/** Shape returned by `rc_api.get_resource_params`. Numbers arrive as strings. */ +export interface RcPriceCurveParams { + coeff_a: string | number; + coeff_b: string | number; + shift: string | number; +} + +export interface RcResourceDynamicsParams { + resource_unit: string | number; + budget_per_time_unit: string | number; + pool_eq: string | number; + max_pool_size: string | number; +} + +export interface RcResourceParamEntry { + resource_dynamics_params: RcResourceDynamicsParams; + price_curve_params: RcPriceCurveParams; +} + +/** + * Per-operation and per-transaction sizing constants. Only the members this + * module needs are declared; the node returns many more. + */ +export interface RcSizeInfo { + resource_state_bytes: { + comment_base_size: number; + comment_permlink_char_size: number; + comment_beneficiaries_member_size: number; + transaction_base_size: number; + [key: string]: number; + }; + resource_execution_time: { + comment_time: number; + comment_options_time: number; + transaction_time: number; + verify_authority_time: number; + [key: string]: number; + }; + [key: string]: Record; +} + +export interface RcResourceParams { + resource_params: Record; + size_info: RcSizeInfo; +} + +/** + * Resource order is consensus-defined (`HIVE_RC_NUM_RESOURCE_TYPES`) and the + * `pool`, `share` and `budget` arrays in rc_stats are indexed by it. + */ +export const RC_RESOURCE_NAMES = [ + "resource_history_bytes", + "resource_new_accounts", + "resource_market_bytes", + "resource_state_bytes", + "resource_execution_time" +] as const; + +export type RcResourceName = (typeof RC_RESOURCE_NAMES)[number]; + +export interface RcCostBreakdown { + resource: RcResourceName; + usage: number; + cost: number; +} diff --git a/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.spec.ts b/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.spec.ts new file mode 100644 index 0000000000..307ec6fffa --- /dev/null +++ b/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.spec.ts @@ -0,0 +1,384 @@ +import { describe, expect, it } from "vitest"; +import { + computeResourceCost, + countCommentResourceUsage, + estimateCommentRcCost, + estimateCommentTransactionBytes +} from "./estimate-comment-rc-cost"; +import { RC_RESOURCE_NAMES } from "../types/resource-params"; +import type { RcResourceParams } from "../types/resource-params"; + +/** + * Ground truth captured from a real rejection on 2026-08-14. The node logs + * usage and cost per resource in `tx_info` when it refuses a transaction, so + * this fixture pins the port to numbers the chain itself produced: + * + * Account: spacecop has 21319011516 RC, needs 23338899909 RC + * cost: [22650133776, 0, 0, 650978626, 37787507] + * usage: [46620, 0, 0, 4241216, 166965 ] + */ +const REJECTION = { + permlink: "who-the-dhf-has-actually", + transactionBytes: 46620, + signatures: 1, + usage: { history: 46620, state: 4241216, execution: 166965 }, + cost: { history: 22650133776, state: 650978626, execution: 37787507, total: 23338899909 }, + poolAtTx: [24091156132, 16787104, 1980851228, 26129897630853, 66076533904], + regen: 2403497928903, + share: [5264, 10000, 533, 1843, 2357] +}; + +const PARAMS: RcResourceParams = { + resource_params: { + resource_history_bytes: { + resource_dynamics_params: { + resource_unit: 1, + budget_per_time_unit: 43403, + pool_eq: 0, + max_pool_size: 0 + }, + price_curve_params: { coeff_a: "10525659774662010880", coeff_b: "211332338", shift: 50 } + }, + resource_new_accounts: { + resource_dynamics_params: { + resource_unit: 10000, + budget_per_time_unit: 797, + pool_eq: 0, + max_pool_size: 0 + }, + price_curve_params: { coeff_a: "16484671763857882971", coeff_b: "1231961", shift: 51 } + }, + resource_market_bytes: { + resource_dynamics_params: { + resource_unit: 10, + budget_per_time_unit: 72338, + pool_eq: 0, + max_pool_size: 0 + }, + price_curve_params: { coeff_a: "14969827235074865152", coeff_b: "15654337", shift: 55 } + }, + resource_state_bytes: { + resource_dynamics_params: { + resource_unit: 1, + budget_per_time_unit: 43546196, + pool_eq: 0, + max_pool_size: 0 + }, + price_curve_params: { coeff_a: "10525659774662010880", coeff_b: "212030656091", shift: 50 } + }, + resource_execution_time: { + resource_dynamics_params: { + resource_unit: 1, + budget_per_time_unit: 40000000, + pool_eq: 0, + max_pool_size: 0 + }, + price_curve_params: { coeff_a: "14969827235074865152", coeff_b: "541062725", shift: 59 } + } + }, + size_info: { + resource_state_bytes: { + comment_base_size: 4237056, + comment_permlink_char_size: 168, + comment_beneficiaries_member_size: 1344, + transaction_base_size: 128 + }, + resource_execution_time: { + comment_time: 66178, + comment_options_time: 6202, + transaction_time: 6622, + verify_authority_time: 94165 + } + } +}; + +const STATS = { pool: REJECTION.poolAtTx, regen: REJECTION.regen, share: REJECTION.share }; + +const within = (actual: number, expected: number, pct: number) => + Math.abs(actual - expected) / expected <= pct / 100; + +describe("countCommentResourceUsage", () => { + const usage = countCommentResourceUsage( + { + transactionBytes: REJECTION.transactionBytes, + permlinkLength: REJECTION.permlink.length, + signatures: REJECTION.signatures + }, + PARAMS.size_info + ); + + // These are exact, not approximate: the formulas are deterministic. + it("reproduces the chain's history_bytes exactly", () => { + expect(usage.resource_history_bytes).toBe(REJECTION.usage.history); + }); + + it("reproduces the chain's state_bytes exactly", () => { + expect(usage.resource_state_bytes).toBe(REJECTION.usage.state); + }); + + it("reproduces the chain's execution_time exactly", () => { + expect(usage.resource_execution_time).toBe(REJECTION.usage.execution); + }); + + it("leaves resources a comment does not touch at zero", () => { + expect(usage.resource_new_accounts).toBe(0); + expect(usage.resource_market_bytes).toBe(0); + }); + + it("scales state_bytes with permlink length", () => { + const longer = countCommentResourceUsage( + { transactionBytes: 100, permlinkLength: 30, signatures: 1 }, + PARAMS.size_info + ); + const shorter = countCommentResourceUsage( + { transactionBytes: 100, permlinkLength: 10, signatures: 1 }, + PARAMS.size_info + ); + expect(longer.resource_state_bytes - shorter.resource_state_bytes).toBe(168 * 20); + }); + + it("charges execution time per signature", () => { + const two = countCommentResourceUsage( + { transactionBytes: 100, permlinkLength: 10, signatures: 2 }, + PARAMS.size_info + ); + const one = countCommentResourceUsage( + { transactionBytes: 100, permlinkLength: 10, signatures: 1 }, + PARAMS.size_info + ); + expect(two.resource_execution_time - one.resource_execution_time).toBe(94165); + }); +}); + +describe("computeResourceCost", () => { + const regenShare = (i: number) => Math.floor((REJECTION.regen * REJECTION.share[i]) / 10000); + + it("prices history_bytes within 1% of the chain", () => { + const cost = computeResourceCost( + PARAMS.resource_params.resource_history_bytes.price_curve_params, + REJECTION.poolAtTx[0], + REJECTION.usage.history, + regenShare(0) + ); + expect(within(cost, REJECTION.cost.history, 1)).toBe(true); + }); + + it("prices state_bytes within 3% of the chain", () => { + const cost = computeResourceCost( + PARAMS.resource_params.resource_state_bytes.price_curve_params, + REJECTION.poolAtTx[3], + REJECTION.usage.state, + regenShare(3) + ); + expect(within(cost, REJECTION.cost.state, 3)).toBe(true); + }); + + it("prices execution_time within 3% of the chain", () => { + const cost = computeResourceCost( + PARAMS.resource_params.resource_execution_time.price_curve_params, + REJECTION.poolAtTx[4], + REJECTION.usage.execution, + regenShare(4) + ); + expect(within(cost, REJECTION.cost.execution, 3)).toBe(true); + }); + + it("keeps full precision on coefficients past Number.MAX_SAFE_INTEGER", () => { + // coeff_a is ~1.05e19. Doing this in floats silently loses the low bits. + expect(Number("10525659774662010880") > Number.MAX_SAFE_INTEGER).toBe(true); + const cost = computeResourceCost( + PARAMS.resource_params.resource_history_bytes.price_curve_params, + REJECTION.poolAtTx[0], + 1, + regenShare(0) + ); + expect(Number.isFinite(cost)).toBe(true); + expect(cost).toBeGreaterThan(0); + }); + + it("returns 0 for empty or unusable input rather than throwing", () => { + const curve = PARAMS.resource_params.resource_history_bytes.price_curve_params; + expect(computeResourceCost(curve, 1, 0, 1)).toBe(0); + expect(computeResourceCost(curve, 1, -5, 1)).toBe(0); + expect(computeResourceCost(curve, 1, 10, 0)).toBe(0); + }); +}); + +describe("total cost against the rejection", () => { + // Composed from the two exported primitives with the transaction size the + // chain reported, so nothing here is circular: the size is an input, not + // something this module derived. + const totalFor = (transactionBytes: number) => { + const usage = countCommentResourceUsage( + { transactionBytes, permlinkLength: REJECTION.permlink.length, signatures: 1 }, + PARAMS.size_info + ); + return RC_RESOURCE_NAMES.reduce((sum, name, index) => { + const entry = PARAMS.resource_params[name]; + const regenShare = Math.floor((REJECTION.regen * REJECTION.share[index]) / 10000); + return ( + sum + + computeResourceCost( + entry.price_curve_params, + REJECTION.poolAtTx[index], + usage[name] * Number(entry.resource_dynamics_params.resource_unit), + regenShare + ) + ); + }, 0); + }; + + it("lands within 1% of what the chain charged", () => { + expect(within(totalFor(REJECTION.transactionBytes), REJECTION.cost.total, 1)).toBe(true); + }); + + it("would have caught the rejection before broadcast", () => { + const SPACECOP_MAX_RC = 21399560550; + // Needed more than the account's entire maximum, so waiting to regenerate + // could never have helped. + expect(totalFor(REJECTION.transactionBytes)).toBeGreaterThan(SPACECOP_MAX_RC); + }); + + it("scales with transaction size, which is the actionable lever", () => { + expect(totalFor(46620)).toBeGreaterThan(totalFor(4662) * 5); + }); +}); + +describe("estimateCommentRcCost", () => { + const op = { + author: "spacecop", + permlink: REJECTION.permlink, + parent_author: "", + parent_permlink: "dhf", + title: "Who the DHF has actually paid", + body: "x".repeat(40000), + json_metadata: "{}" + }; + + it("attributes most of the cost to history_bytes on a large post", () => { + const result = estimateCommentRcCost({ op, rcParams: PARAMS, rcStats: STATS }); + const history = result.breakdown.find((b) => b.resource === "resource_history_bytes"); + + expect(history!.cost / result.cost).toBeGreaterThan(0.9); + }); + + it("charges more once a companion comment_options is attached", () => { + const plain = estimateCommentRcCost({ op, rcParams: PARAMS, rcStats: STATS }); + const withOptions = estimateCommentRcCost({ + op, + options: { beneficiaries: [{ account: "ecency", weight: 500 }] }, + rcParams: PARAMS, + rcStats: STATS + }); + + expect(withOptions.cost).toBeGreaterThan(plain.cost); + expect(withOptions.transactionBytes).toBeGreaterThan(plain.transactionBytes); + }); + + it("charges state bytes per beneficiary", () => { + const one = estimateCommentRcCost({ + op, + options: { beneficiaries: [{ account: "a", weight: 1 }] }, + rcParams: PARAMS, + rcStats: STATS + }); + const three = estimateCommentRcCost({ + op, + options: { + beneficiaries: [ + { account: "a", weight: 1 }, + { account: "b", weight: 1 }, + { account: "c", weight: 1 } + ] + }, + rcParams: PARAMS, + rcStats: STATS + }); + const stateOf = (r: typeof one) => + r.breakdown.find((b) => b.resource === "resource_state_bytes")!.usage; + + expect(stateOf(three) - stateOf(one)).toBe(1344 * 2); + }); + + it("is not ready until both queries resolve, so callers cannot warn early", () => { + expect(estimateCommentRcCost({ op, rcParams: undefined, rcStats: STATS }).ready).toBe(false); + expect(estimateCommentRcCost({ op, rcParams: PARAMS, rcStats: undefined }).ready).toBe(false); + }); +}); + +const REAL_TX = { + trueBytes: 1823, + signatures: 1, + op: { + parent_author: "", + parent_permlink: "hive-193084", + author: "gazzarin", + permlink: "uhccwy21z33fuo4jmeu790", + title: "\u00a1Claro! Aqu\u00ed tienes algunas ideas de t\u00edtulos de publicaciones breves para Twitter relacionadas con viajes:\n\n1", + body: "\n\n\n
![image](https://pixabay.com/get/g4b2ffaa2da0850605268cb320bf636dffdca605202cd50fb4083d4e664ae5d0c71e43d25dbc484eb77d892ed189dd8817891b4ca971e2d82d9156df3cbc2c7c2_640.jpg)
\n\n***\n\n1. \ud83c\udf0d\u2708\ufe0f \"La vida es un viaje, no un destino. \u00a1Explora cada rinc\u00f3n del mundo! #Viajes #Aventura\"\n \n2. \ud83c\udfd6\ufe0f \"\u00bfPlaya o monta\u00f1a? \u00bfCu\u00e1l es tu escapada so\u00f1ada? \ud83c\udfd4\ufe0f #ViajarEsVivir\"\n\n3. \ud83c\udf5c \"Descubrir nuevos sabores es una de las mejores partes de viajar. \u00bfCu\u00e1l ha sido tu platillo favorito? #Gastronom\u00eda #Viajes\"\n\n4. \ud83d\udcf8 \"Captura momentos, no cosas. \u00a1Haz que cada viaje cuente! #Fotograf\u00edaDeViajes #Recuerdos\"\n\n5. \ud83d\ude82 \"Viajar en tren: la forma m\u00e1s rom\u00e1ntica de ver el mundo. \u00bfCu\u00e1l es tu ruta favorita? #Tren #Aventuras\"\n\n6. \ud83d\uddfa\ufe0f \"Siempre lleva un mapa, pero no tengas miedo de perderte. \u00a1Las mejores aventuras est\u00e1n en lo inesperado! #Exploraci\u00f3n\"\n\n7. \ud83c\udf04 \"El amanecer en la monta\u00f1a es un espect\u00e1culo que no te puedes perder. \u00bfD\u00f3nde has visto el mejor? #Naturaleza #Viajes\"\n\n8. \ud83c\udfd9\ufe0f \"Las ciudades tienen historias que contar. \u00bfCu\u00e1l es la m\u00e1s fascinante que has escuchado? #Cultura #TravelTales\"\n\n9. \ud83c\udf0c \"Bajo el cielo estrellado, todos los problemas parecen lejanos. \u00bfD\u00f3nde has visto m\u00e1s estrellas? #Astroturismo\"\n\n10. \ud83e\uddf3 \"Empaca ligero, viaja lejos. \u00a1Menos es m\u00e1s! #ConsejosDeViaje #Minimalismo\" \n\n\u00a1Espero que estas ideas te inspiren!\n\n***\n\n", + json_metadata: "{\"app\": \"dBuzz/v3.0.0\", \"tags\": [\"trip\", \"life\", \"nature\", \"kr\", \"waivio\", \"neoxian\", \"leo\", \"inleo\", \"cent\", \"oneup\", \"pob\", \"proofofbrain\", \"hustler\", \"pal\", \"pimp\"], \"shortForm\": \"true\"}", + } +}; + +describe("estimateCommentTransactionBytes", () => { + // Read back from the chain with `get_transaction_hex`, so this validates the + // serialization model against real bytes rather than against itself. The + // model was checked byte-exact on eight such transactions, including one + // carrying comment_options. + it("matches a real transaction byte for byte", () => { + expect( + estimateCommentTransactionBytes({ op: REAL_TX.op, signatures: REAL_TX.signatures }) + ).toBe(REAL_TX.trueBytes); + }); + + it("counts UTF-8 bytes, not UTF-16 code units", () => { + const base = { + author: "a", + permlink: "b", + parent_author: "", + parent_permlink: "c", + title: "t", + json_metadata: "{}" + }; + const ascii = estimateCommentTransactionBytes({ op: { ...base, body: "aaaa" } }); + const accented = estimateCommentTransactionBytes({ op: { ...base, body: "áááá" } }); + const emoji = estimateCommentTransactionBytes({ op: { ...base, body: "🐝🐝🐝🐝" } }); + + // 1, 2 and 4 bytes per character respectively + expect(accented - ascii).toBe(4); + expect(emoji - ascii).toBe(12); + }); + + it("charges 65 bytes for each additional signature", () => { + const one = estimateCommentTransactionBytes({ op: REAL_TX.op, signatures: 1 }); + const two = estimateCommentTransactionBytes({ op: REAL_TX.op, signatures: 2 }); + + expect(two - one).toBe(65); + }); + + it("grows the length prefix as a field crosses a varint boundary", () => { + const base = { + author: "a", + permlink: "b", + parent_author: "", + parent_permlink: "c", + title: "t", + json_metadata: "{}" + }; + const under = estimateCommentTransactionBytes({ op: { ...base, body: "x".repeat(127) } }); + const over = estimateCommentTransactionBytes({ op: { ...base, body: "x".repeat(128) } }); + + // one more content byte plus one more varint byte + expect(over - under).toBe(2); + }); + + it("includes the companion comment_options in the size", () => { + const plain = estimateCommentTransactionBytes({ op: REAL_TX.op }); + const withOptions = estimateCommentTransactionBytes({ + op: REAL_TX.op, + options: { beneficiaries: [{ account: "ecency", weight: 500 }] } + }); + + expect(withOptions).toBeGreaterThan(plain); + }); +}); diff --git a/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.ts b/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.ts new file mode 100644 index 0000000000..4671c6fbe8 --- /dev/null +++ b/packages/sdk/src/modules/resource-credits/utils/estimate-comment-rc-cost.ts @@ -0,0 +1,296 @@ +import { utf8ByteLength, varintByteLength } from "@/modules/core/utf8"; +import { + RC_RESOURCE_NAMES, + type RcCostBreakdown, + type RcPriceCurveParams, + type RcResourceName, + type RcResourceParams, + type RcSizeInfo +} from "../types/resource-params"; +import type { RcStats } from "../types/stats"; + +/** + * What the chain actually charges for publishing a comment, rather than the + * network-average cost of an average comment. + * + * The average is a poor guide for posts: it is dominated by short replies, + * while a long post is charged mostly on `history_bytes`, which is the + * serialized transaction size. A real case: an account holding 21.3B RC was + * told it could afford 17 posts, then a 46,620-byte post was rejected needing + * 23.3B RC, more than that account's entire maximum. + * + * This is a direct port of `resource_credits::compute_cost` and the + * `comment_operation` arm of `count_resources` from hive, so it tracks what + * the node does instead of approximating it. Verified against a real + * rejection: usage reproduces exactly and total cost lands within 0.3%, the + * residual coming from `share` being published rounded to four digits. + */ + +/** + * Fixed transaction header: ref_block_num(2) + ref_block_prefix(4) + + * expiration(4) + the extensions varint(1). + */ +const TRANSACTION_HEADER_BYTES = 11; +/** Compact signature, 65 bytes each. */ +const SIGNATURE_BYTES = 65; +/** asset = amount int64(8) + precision(1) + symbol(7). */ +const ASSET_BYTES = 16; + +const big = (v: string | number): bigint => BigInt(typeof v === "string" ? v : Math.trunc(v)); + +/** + * Port of `resource_credits::compute_cost` (libraries/chain/rc/rc_utility.cpp). + * + * BigInt is required, not stylistic: `coeff_a` is ~1.05e19, well past + * Number.MAX_SAFE_INTEGER, so float arithmetic loses the low bits and the + * result drifts. + */ +export function computeResourceCost( + curve: RcPriceCurveParams, + pool: number, + resourceCount: number, + regenShare: number +): number { + if (resourceCount <= 0 || regenShare <= 0) { + return 0; + } + + const coeffA = big(curve.coeff_a); + const coeffB = big(curve.coeff_b); + const shift = big(curve.shift); + + // The node shifts before multiplying by the resource count, because + // regen * coeff_a already risks overflowing 128 bits. Order matters. + let num = (big(regenShare) * coeffA) >> shift; + num += 1n; + num *= big(resourceCount); + + const denom = coeffB + (pool > 0 ? big(pool) : 0n); + if (denom === 0n) { + return 0; + } + + return Number(num / denom + 1n); +} + +export interface CommentResourceUsageInput { + /** Byte length of the serialized transaction. */ + transactionBytes: number; + permlinkLength: number; + /** Signatures on the transaction; a normal post carries one. */ + signatures?: number; + /** + * Beneficiary count on the companion comment_options, when publish appends + * one. The chain counts resources for every operation in the transaction, + * not just the comment. + */ + beneficiaries?: number; + hasCommentOptions?: boolean; +} + +/** + * Port of the `comment_operation` and `comment_options_operation` arms of + * `count_resources` (libraries/chain/rc/resource_count.cpp). Reproduces the + * chain's numbers exactly, see the spec. + */ +export function countCommentResourceUsage( + { + transactionBytes, + permlinkLength, + signatures = 1, + beneficiaries = 0, + hasCommentOptions = false + }: CommentResourceUsageInput, + sizeInfo: RcSizeInfo +): Record { + const state = sizeInfo.resource_state_bytes; + const exec = sizeInfo.resource_execution_time; + + return { + resource_history_bytes: transactionBytes, + resource_new_accounts: 0, + resource_market_bytes: 0, + resource_state_bytes: + state.comment_base_size + + state.comment_permlink_char_size * permlinkLength + + state.transaction_base_size + + // comment_payout_beneficiaries is visited from comment_options + state.comment_beneficiaries_member_size * beneficiaries, + resource_execution_time: + exec.comment_time + + exec.transaction_time + + exec.verify_authority_time * signatures + + (hasCommentOptions ? exec.comment_options_time : 0) + }; +} + +export interface CommentLike { + author: string; + permlink: string; + parent_author: string; + parent_permlink: string; + title: string; + body: string; + json_metadata: string; +} + + +/** A beneficiary route as it appears in comment_options extensions. */ +export interface BeneficiaryRoute { + account: string; + weight: number; +} + +/** + * The comment_options operation publish appends when the author sets + * beneficiaries or a non-default reward split. + */ +export interface CommentOptionsLike { + beneficiaries?: BeneficiaryRoute[]; +} + +/** Serialized bytes of one string field: its varint length plus its bytes. */ +const stringFieldBytes = (value: string): number => { + const length = utf8ByteLength(value); + return varintByteLength(length) + length; +}; + +const commentOperationBytes = (op: CommentLike): number => + 1 + // operation variant id + stringFieldBytes(op.parent_author) + + stringFieldBytes(op.parent_permlink) + + stringFieldBytes(op.author) + + stringFieldBytes(op.permlink) + + stringFieldBytes(op.title) + + stringFieldBytes(op.body) + + stringFieldBytes(op.json_metadata); + +const commentOptionsBytes = (op: CommentLike, options: CommentOptionsLike): number => { + const beneficiaries = options.beneficiaries ?? []; + let bytes = + 1 + // operation variant id + stringFieldBytes(op.author) + + stringFieldBytes(op.permlink) + + ASSET_BYTES + // max_accepted_payout + 2 + // percent_hbd + 2; // allow_votes + allow_curation_rewards + + bytes += varintByteLength(beneficiaries.length > 0 ? 1 : 0); + if (beneficiaries.length > 0) { + bytes += 1 + varintByteLength(beneficiaries.length); // extension variant id + route count + beneficiaries.forEach((route) => { + bytes += stringFieldBytes(route.account) + 2; // weight is uint16 + }); + } + return bytes; +}; + +export interface CommentTransactionInput { + op: CommentLike; + /** Present when publish appends comment_options for beneficiaries or rewards. */ + options?: CommentOptionsLike; + signatures?: number; +} + +/** + * Serialized size of the transaction that will carry this comment. + * + * This models Hive's binary encoding rather than approximating it: a fixed + * header, one varint-prefixed field per string, and 65 bytes per signature. + * Verified byte-exact against eight real transactions read back with + * `get_transaction_hex`, including one carrying comment_options. + */ +export function estimateCommentTransactionBytes({ + op, + options, + signatures = 1 +}: CommentTransactionInput): number { + const operations = [commentOperationBytes(op)]; + if (options) { + operations.push(commentOptionsBytes(op, options)); + } + + return ( + TRANSACTION_HEADER_BYTES + + varintByteLength(operations.length) + + operations.reduce((sum, bytes) => sum + bytes, 0) + + varintByteLength(signatures) + + SIGNATURE_BYTES * signatures + ); +} + +export interface EstimateCommentRcCostInput { + op: CommentLike; + /** Companion comment_options, when the author set beneficiaries or rewards. */ + options?: CommentOptionsLike; + rcParams: RcResourceParams | undefined; + rcStats: Pick | undefined; + signatures?: number; +} + +export interface CommentRcCostEstimate { + /** False until both queries have resolved; callers must not warn on this. */ + ready: boolean; + cost: number; + transactionBytes: number; + breakdown: RcCostBreakdown[]; +} + +const EMPTY: CommentRcCostEstimate = { + ready: false, + cost: 0, + transactionBytes: 0, + breakdown: [] +}; + +/** Total RC the chain will charge to broadcast this comment. */ +export function estimateCommentRcCost({ + op, + options, + rcParams, + rcStats, + signatures = 1 +}: EstimateCommentRcCostInput): CommentRcCostEstimate { + if (!rcParams?.resource_params || !rcParams.size_info || !rcStats?.pool || !rcStats.share) { + return EMPTY; + } + + const transactionBytes = estimateCommentTransactionBytes({ op, options, signatures }); + const usage = countCommentResourceUsage( + { + transactionBytes, + permlinkLength: utf8ByteLength(op.permlink), + signatures, + beneficiaries: options?.beneficiaries?.length ?? 0, + hasCommentOptions: !!options + }, + rcParams.size_info + ); + + const regen = Number(rcStats.regen); + let cost = 0; + const breakdown: RcCostBreakdown[] = []; + + RC_RESOURCE_NAMES.forEach((name, index) => { + const entry = rcParams.resource_params[name]; + const pool = Number(rcStats.pool[index] ?? 0); + const share = Number(rcStats.share[index] ?? 0); + if (!entry || share <= 0) { + return; + } + + // `usage` is scaled by the resource unit before pricing. It is 1 for the + // resources a comment touches, but market bytes and new accounts are not. + const scaled = usage[name] * Number(entry.resource_dynamics_params.resource_unit ?? 1); + // rc_stats publishes `share` as weight/divisor scaled to 10,000. Kept in + // BigInt: regen is ~2.4e12 and the product is past the safe-integer range + // for larger shares. + const regenShare = Number((BigInt(regen) * BigInt(share)) / 10000n); + const resourceCost = computeResourceCost(entry.price_curve_params, pool, scaled, regenShare); + + cost += resourceCost; + breakdown.push({ resource: name, usage: scaled, cost: resourceCost }); + }); + + return { ready: true, cost, transactionBytes, breakdown }; +} diff --git a/packages/sdk/src/modules/resource-credits/utils/index.ts b/packages/sdk/src/modules/resource-credits/utils/index.ts index dc1c0943f7..a6198357f4 100644 --- a/packages/sdk/src/modules/resource-credits/utils/index.ts +++ b/packages/sdk/src/modules/resource-credits/utils/index.ts @@ -1 +1,2 @@ export * from "./estimate-rc-precheck"; +export * from "./estimate-comment-rc-cost"; diff --git a/packages/wallets/CHANGELOG.md b/packages/wallets/CHANGELOG.md index 0bd2165058..5f4cba6f26 100644 --- a/packages/wallets/CHANGELOG.md +++ b/packages/wallets/CHANGELOG.md @@ -1,5 +1,12 @@ # @ecency/wallets +## 5.0.84 + +### Patch Changes + +- Updated dependencies []: + - @ecency/sdk@2.3.84 + ## 5.0.83 ### Patch Changes diff --git a/packages/wallets/package.json b/packages/wallets/package.json index dfb3d16cb1..91da2673b4 100644 --- a/packages/wallets/package.json +++ b/packages/wallets/package.json @@ -1,7 +1,7 @@ { "name": "@ecency/wallets", "private": false, - "version": "5.0.83", + "version": "5.0.84", "description": "Ecency wallets", "repository": { "type": "git",